I have an abstract functor class that overloads operator() and derived objects that implement it.
I have a function (part of another class) that tries to take an Array of these functor classes and tries to pass a pointer to a member function to the std algorithm for_each(), here is a overview of what I’m doing:
EDIT: I have re-cleaned it and put the old small example for clarity.
class A{
operator()(x param)=0;
operator()(y param)=0;
}
class B: public A{
operator()(x param); //implemented
operator()(y param);
}
...// and other derived classes from A
void ClassXYZ::function(A** aArr, size_t aSize)
{
...//some code here
for(size_t i = 0; i< aSize; i++){
A* x = aArr[i];
for(v.begin(), v.end(), ...//need to pass pointer/functor to right operator() of x here
..//other code
}
I’ve tried a few ways and I can’t figure out how to get it to work, I need to use the abstract type as I could have different derived types but they will all have to implement the same operator()(param x) function.
I just need the for_each() function to be able to call the member function operator()(param x). I have a different function where it has concrete implementations and simply passes an instance of those and it works. I’m trying to achieve a similar effect here but without the knowledge of what concrete classes I’m given.
What am I doing wrong?
If I understand what you want to do, there are quite a few errors in your code snippet:
sizeof aArris wrong, you need to pass the size explicitly (noticed by ChrisW)virtualspecifier on the original declaration ofoperator()()forloop ends as there’s no matching}(I suspect it shouldn’t be there at all)Here’s some code that will loop through an array of
A(orA-derived) objects and calloperator()on each one, passing across a passed-in argument as theparamparameter:mem_fun()is necessary to convert a 1-parameter member function pointer to a 2-parameter function object;bind2nd()then produces from that a 1-parameter function object that fixes the argument supplied tofunction()as the 2nd argument. (for_each()requires a 1-parameter function pointer or function object.)EDIT: Based on Alex Tingle’s answer, I infer that you might have wanted
function()to do many things on a singleA-derived object. In that case, you’ll want something like: