2013-04-15 59 views
0

標題總結了我的問題 - 我需要一個指向模板類方法的指針的泛型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); 

回答

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

希望有所幫助。

+0

謝謝,C++ 11的 「使用」 關鍵字的作品。 – Brandon

2

在C++ 11:

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

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

謝謝,這個工程。 – Brandon