Possible Duplicate:
how to specify a pointer to an overloaded function?
I have a library which has a class defined as:
struct ClassA
{
static ClassA foo(long);
static ClassA foo(double);
}
I need to get the addresses of both of those functions. The code I am currently trying gives error C2440: cannot convert from ‘overloaded-function’ to ‘…’
ns::ClassA (ns::ClassA::*ClassA_foo1)(long) = &ns::ClassA::foo;
ns::ClassA (ns::ClassA::*ClassA_foo2)(double) = &ns::ClassA::foo;
I thought it might be the fact that they are static, but placing static either before or after the return type gives the same error.
The fact that the function is overloaded is not really relevant. The real issue here is the difference between a function-pointer and a member-function-pointer. I’ll run through some examples without overloading.
Solution: Either remove the
static, in order to define them as member-functions. Or else replacens::ClassA::*ClassA_foo1with*ClassA_foo1. I think you want the latter. (But I actually recommend you usetypedef, as others have already suggested).Consider these two:
and
In the former case, foo is
staticand is therefore a typical function, and can be stored in a function-pointer:If you remove the
static, then it is not a function any more, it’s a member function. And pointers-to-member-functions are different from pointers-to-functions, they must be executed with an object that will be thethisobject on which the method is called.The type of a function pointer includes the type of the return value and the type of the parameters. But the type of a pointer-to-member-function must also include the type of the
thisobject – you wouldn’t expect to be able to run a method from aCircleon an object of typeBankAccount.Declaring a pointer-to-function:
Declaring a pointer-to-member-function:
This last line is the interesting one. At first glance, you might think that
R (A::*v) (P1,P2)declares a normal function-pointer and places the resulting variablevinto theAscope. But it does not. Instead it defines a pointer-to-member-function which operates on objects of typeA.