2
votes

plenty of great examples of maps of function pointers to static and non-static members - I have not been able to find one which uses class templates as well.

I'm having trouble understanding this error message when using the code below:

tclass.H:34:16: error: cannot convert ‘int (*)(MyPair*)’ 
to ‘std::map, int (MyPair::*)(MyPair*), std::less >, std::allocator, 
int (MyPair::*)(MyPair*)> > >::mapped_type {aka int (MyPair::*)(MyPair*)}’ 
in assignment

f[ "max" ] = &MyPair::max;

Code in question is:

#include <map>

using namespace std;

template <class T>
class MyPair {
public:
    MyPair (T first, T second) : 
    a( first ), b( second ) {}

    static T max( MyPair* );

    T call( const string& name ) {
        func f = s_funcs[ name ];
        return ( this->*f )( this );
    }

protected:
    typedef T ( MyPair::*func ) ( MyPair<T>* );
    typedef map<string, func> FuncMap;

    static FuncMap initMap();
    static FuncMap s_funcs;

    T a, b;
};

template <class T>
typename MyPair<T>::FuncMap MyPair<T>::s_funcs = initMap();

template <class T>
typename MyPair<T>::FuncMap MyPair<T>::initMap() {
    FuncMap f;
    f[ "max" ] = &MyPair<T>::max;
    return f;
} 

template <class T>
T MyPair<T>::max ( MyPair<T>* pair ) {
    T retval;
    retval = pair -> a > pair -> b ? 
    pair -> a : 
    pair -> b;
    return retval;
}
2

2 Answers

2
votes

(Cleaning out a little cruft from the message...)

error: cannot convert int (*)(MyPair*) to int (MyPair::*)(MyPair*) in assignment

You have defined T as a pointer to member function:

typedef T ( MyPair::*func ) ( MyPair<T>* );

However, a static member function is not assignable to that type. It assigns to a regular function pointer.

If you want your map to hold static functions, change T to:

typedef T ( *func ) ( MyPair<T>* );
0
votes

A pointer to a member would be better named as "pointer to non-static member". This is why it is necessary to have two bits of information (the pointer to member, and a pointer to an instance of the class) in order to call pointers to member functions.

From a language perspective, pointer to function is different and incompatible type from a pointer to member function. Your compiler is complaining because it cannot convert one to the other.

&MyPair::max() is a pointer to a static function, which is something distinct from a pointer to a member function. Your set f maps strings into pointers to member functions, so cannot hold a pointer to a static function.