【问题标题】:Typedef for pointer to a template class method指向模板类方法的指针的 typedef
【发布时间】:2013-04-15 03:15:46
【问题描述】:
标题总结了我的问题 - 我需要一个泛型 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 );
【问题讨论】:
标签:
c++
templates
c++11
typedef
【解决方案1】:
在 C++11 中:
template<typename TYPE>
using ParticleMethodPtr = const TYPE&(MyClass<TYPE>::*)() const;
ParticleMethodPtr<int> p = &MyClass<int>::get;
【解决方案2】:
这是不允许的,正如你自己所看到的那样。
你可以这样做:
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);
希望对您有所帮助。