Question

I need an universal function pointer. I made this simple code below, but g++ gives me an error if I try to assign a value to the function pointer.

TestMain.cpp: In function ‘int main(int, const char**)’:
TestMain.cpp:11:21: error: overloaded function with no contextual type information

The code:

class MyClass{
public:
    void func(char ch){}
};

template <class Class, class ret, class Arg1>
int Foo(ret (Class::* obj)(Arg1)){
}

int main(int argc, char const *argv[]){
    Foo = &MyClass::func;
    return 0;
}
Was it helpful?

Solution

The declaration of a pointer to member function would be in your case

void (MyClass::*mf1)(char) = &MyClass::func; // (1)

So the syntax to a pointer to member function is fundamentaly different. Also you can't declare a templated function pointer, so you can translate the above into templates, the following is illegal

template <class Class, class ret, class Arg1> // (2)
ret (Class::*pMf)(Arg1);

it fails with the following error

1>StackOverflow.cpp(23): error C2998: 'ret (__cdecl Class::* __cdecl pMf)(Arg1)' : cannot be a template definition

What you can do

Solution 1 : alias templates

template<typename Class, typename ret, typename Arg1>
using pMemFun = ret (Class::*)(Arg1);

int main()
{
    pMemFun<MyClass, void, char> pF = &MyClass::func;
    return 0;
}

Solution 2 : helper struct

Thnx 2 dyp for the tip on compiling in gcc.

Take a look at the following structure

template <class Class, class ret, class Arg1>
struct mFunPtr
{
    typedef ret (Class::*ptr)(Arg1);
};

This is a workaround to templatize the type of a pointer to member function. Using the above would allow code like

mFunPtr<MyClass, void, char>::ptr fPtr = &MyClass::func; // (3)

Now, is (3) + a struct definition better than (1) ? That's up to your taste;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top