I'm trying to store member function pointers by templates like this: (This is a simplified version of my real code)
template<class Arg1>
void connect(void (T::*f)(Arg1))
{
//Do some stuff
}
template<class Arg1>
void connect(void (T::*f)())
{
//Do some stuff
}
class GApp
{
public:
void foo() {}
void foo(double d) {}
};
Then I want to do like the following for every overloaded methods in GApp:
connect(&GApp::foo);
Calling this for foo()
is ok, but how can I call this for foo(double d)
? Why isn't the following working?
connect((&GApp::foo)(double));
It will give me
syntax error : 'double' should be preceded by ')'
I don't understand the syntax which must be used here. This may be a stupid qustion, but can any one help me on this?
My Original code is like this,
connectors....
Signals...
Application...
Finaly, connecting...
There is template classs for signals (which are not mention here). I hope now it is more clear the situation. (or is it same as previouse ?). That second connection will WORK if there isn't foo() (only foo(double)). That is the thing my code hurt me. :(
You can try explicitly casting the pointer, to let it know which one to select, like this:
disclaimer: haven't tested it
The C++ Programming Language, 3E, Section 7.7, p159:
As far as I know (haven't checked), the same applies to member functions. So the solution is probably to split across two lines:
becomes:
Never call variables
tmp
;-)I would guess that newacct's cast is safe too, for exactly the same reason. Casting to
void (GApp::*)(double)
is defined to be the same as initializing a temporary of typevoid (GApp::*)(double)
. Since the expression used to initialize it is&GApp::foo
, I would expect the same magic to apply to the cast as applies to any other initialization with an overloaded function. Stroustrup doesn't say "initializing a pointer-to-function variable", he says "initializing a pointer-to-function". So that should include temporaries.So if you prefer a one-liner:
However, I'm assuming that the standard has the same idea of consistency as I do, and I haven't checked.
Using boost::function library...
Your code as written doesn't compile. I've make some "assumptions" about what you wanted to do, and have changed the code.
To summarise, you can call the correct function by explicitly specifying the function parameter type:
If the connect methods are members of a class template, then it is only necessary to specify the class type once:
UPDATE:
In response to the new code sample, all the information is being passed in. The "rare" case is the 'signal_void' case as this is where the signal has a template argument, but the member function doesn't. Therefore we special case that example and then we're done. The following now compiles:
This is working,
Why is that ?
EDIT
hmm.. yeah. It is same as newacct's solution. Can anyone give a solution pls?