Typedef指向模板类方法的指针

时间:2013-04-15 03:15:46

标签: c++ templates c++11 typedef

标题总结了我的问题 - 我需要一个泛型typedef作为指向模板类方法的指针,如下面的代码所述。 typedef必须是通用的。

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 );

2 个答案:

答案 0 :(得分:2)

在C ++ 11中:

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

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

答案 1 :(得分:1)

这是不允许的,正如你自己所见。

你可以这样做:

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

现在您可以将其用作:

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

(obj.*memfun)(100);

您可以使用C ++ 11模板别名使其更简单:

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

然后将其用作:

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

(obj.*memfun)(100);

希望有所帮助。

相关问题