Brandon
Brandon

Reputation: 503

Typedef for pointer to a template class method

The title sums my question up - I need a generic typedef for a pointer to a template class method, as explained in the code below. The typedef needs to be generic.

template<typename TYPE>
struct MyClass {
    const TYPE& get() const {}
};

// this is okay:
typedef void (MyClass<int>::*ParticleMethodPtr)( int );

// now I just need to typedef this so I can
// use the pointer on methods other than int

// using typedef, not okay:
template< TYPE >
typedef void (MyClass<TYPE>::*ParticleMethodPtr)( TYPE );

Upvotes: 1

Views: 1363

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361802

That is not allowed, as you've seen yourself.

You can do this:

template<typename T>
struct member_pointer
{
    typedef void (MyClass<T>::*function_type)(T);
};

Now you can use this as:

member_pointer<int>::function_type memfun = &MyClass<int>::some_func;

(obj.*memfun)(100);

You can use C++11 template alias to make it simpler as:

template<typename T>
using mem_function = typename member_pointer<T>::function_type;

then use it as:

mem_function<int> memfun = &MyClass<int>::some_func;

(obj.*memfun)(100);

Hope that helps.

Upvotes: 1

Jesse Good
Jesse Good

Reputation: 52405

In C++11:

template<typename TYPE>
using ParticleMethodPtr = const TYPE&(MyClass<TYPE>::*)() const;

ParticleMethodPtr<int> p = &MyClass<int>::get;

Upvotes: 2

Related Questions