2

Let's say I have this public method inside a class:

uli returnSum()
{
    for_each(i, j, doSum);
    return this->sum;
}

void doSum(short int y) is a private method of the very same class. How would I pass it as an argument to for_each?

Using the syntax above I'm getting error: must use .* or ->* to call pointer-to-member function in __f (...)'. Neither is this->*doSum working.

I read something about creating a pointer towards that member function and passing it as an argument but I'm not quite sure how to do it.

Tedy S.
  • 89
  • 6

2 Answers2

2

You could use std::bind, like this

std::for_each(i, j, std::bind(&MyClass::doSum, this));
2

Take a look at the following example:

#include <iostream>
using namespace std;

class Test {
  public:
    int fun1(int x) { return x+1; }
};

typedef int (Test::*PtrType)(int);

void call(Test& self, PtrType prt) {
    cout << (self.*ptr)(2) << endl;
}

int main() {
    Test t;
    call(t, &Test::fun1);
    return 0;
}

The line typedef int (Test::*PtrType)(int); defines simple name for the type to the class method. The parenthesis around (Test::*PtrType) are important; PtrType is the new defined type (Although you could do without the typedef, and put the whole signature in the call function arguments, such approach is strongly discouraged).

The expression (self.*ptr)(2) calls the method pointed by your pointer ptr, passing 2 as its argument. Again the key point is putting parenthesis around (self.*ptr).

The last point to remember is that you cannot skip & when setting the value of the pointer (&Test::fun1), even as it is possible with regular function.

You can make your code a little neater, if you use templates:

template <typename PtrT>
void call(Test& self, PtrT ptr) {
    cout << (self.*ptr)(2) << endl;
}

No typedef is necessary in such case, however, you must still remember about parenthesis in the invocation.

If you are compiling with the new C++0x standard, you can use std::function or std::bind.

Maciek D.
  • 2,754
  • 1
  • 20
  • 17