2013-01-16 78 views
1

时,这是我尽量做到:成员函数指针语法声明一个模板

class MyClass 
{ 
    public: 
    template<typename T> 
    void whenEntering(const std::string& strState, 
         T& t, 
         void T::(*pMemberFunction)(void)) /// compilation fails here 
    { 
     t.(*pMemberFunction)(); // this line is only an example 
    } 
} 

它是一种回调系统的反应,一些事件我收到。

但是视觉2010,我下面的编译错误:

error C2589: '(' : illegal token on right side of '::' 

我可能是错的指针到成员语法...但我也害怕我可能不会定义模板此方式...你有什么想法吗?

回答

6

你想void (T::*pMemberFunction)(void)

另一个问题是可能只是在您的示例使用一个错字,但调用成员函数使用.*作为一个单一的运营商;你不能有一个(他们之间,甚至空白。我猜这是一个错字,因为它几乎对付这个指针到成员运营商有怪异的运算符优先级的正确方法:

(t.*pMemberFunction)(); 
+0

现在编译罚款! –

1

有在你的代码的几个问题。特别是,声明一个成员函数指针的语法是void (T::* pMemberFunction)(void)

总的来说,这是你的代码应该如何看起来像:

class MyClass 
{ 
    public: 
    template<typename T> 
    void whenEntering(const std::string& strState, 
         T& t, 
         void (T::* pMemberFunction)(void) 
           ) /// this fails 
    { 
     t.*pMemberFunction(); // this line is only an example 
    } 
};