
Class function pointer does not evaluate to a function
Quote:
> I'm using Visual Studio .NET and I would like to do the following, which
I'm
> fairly certain it's legal; (there's even an example of it in MSDN!) But
I'm
> getting error C2064: term does not evaluate to a function instead:
> class A
> {
> public:
> int AsFunc(int f) { return f; }
> int (A::*pfn)(int);
> };
> void main()
> {
> A a;
> a.pfn = &A::AsFunc;
> cout << a.pfn(1.5); // Error C2064
> }
> Does anyone know how to do this properly? Or should this work?
You're missing the closure. "closure" means that you have to bind a pointer
to member function with an instance to be able to actually perform the call.
a.pfn is a pointer to member function. The fact that it's also a member of A
it doesn't mean that it's automatically bound to an instance. Let me
clarify: if you define it outside, the correct code is:
class A
{
public:
int AsFunc(int f) { return f; }
Quote:
};
int (A::*pfn)(int);
int main(void)
{
A a;
pfn = &A::AsFunc;
cout << (a.*pfn)(1);
Quote:
}
Notice the use of operator ".*" instead of operator "." to bind a pointer to
member function to an instance of the class (it's the closure).
If you keep pfn within the class definition, like in your example, you
should modify your code as: "(a.*(a.pfn))(1)", since you're calling operator
.* to bind the instance "a" to the pointer of member function "a.pfn".
Of course, it looks ugly. You should be using a different approach, and
probably also some binder facilities (look into Boost's bind and Boost's
function for example).
Giovanni Bajo