2010-09-16 174 views
3

我有一个方法调用延迟功能类:模板函数指针

//in MyClass declaration: 
typedef void (MyClass::*IntFunc) (int value); 
void DelayedFunction (IntFunc func, int value, float time); 
class TFunctorInt 
{ 
public: 
    TFunctorInt (MyClass* o, IntFunc f, int v) : obj (o), func (f), value (v) {} 
    virtual void operator()(); 
protected: 
    MyClass* obj; 
    IntFunc func; 
    int value; 
}; 
//in MyClass.cpp file: 
void MyClass::DelayedFunction (IntFunc func, int value, float time) 
{ 
    TFunctorBase* functor = new TFunctorInt (this, func, value); 
    DelayedFunctions.push_back (TDelayedFunction (functor, time)); // will be called in future 
} 
void MyClass::TFunctorInt::operator()() 
{ 
    ((*obj).*(func)) (value); 
} 

我想使模板仿函数。第一个问题是:

template <typename T> 
typedef void (MyClass::*TFunc<T>) (T param); 

导致编译器错误:“typedef'的模板声明”。 什么可能是一个解决方案?

PS:基于http://www.coffeedev.net/c++-faq-lite/en/pointers-to-members.html#faq-33.5

+1

可能的重复[替代模板声明的typedef](http://stackoverflow.com/questions/3708593/alternative-to-template-declaration-of-typedef) – kennytm 2010-09-16 14:54:37

+0

纠正我,如果我错了(这个语法((* obj)。*(func))(value)'拼写成'obj - > * func(value)''代替? – sbi 2010-09-16 14:55:48

+0

@sbi:'(obj - > * func)(value)'确切地说。 – 2010-09-16 14:57:17

回答

10

有C中没有模板的typedef ++代码。在C++ 0x中有这样的扩展。在此期间,做

template <typename T> 
struct TFunc 
{ 
    typedef void (MyClass::*type)(T param); 
}; 

,并使用TFunc<T>::type只要你会用TFunc<T>(与typename如果依赖于上下文前缀)。

+2

'+ 1'比我快36secs! ':)' – sbi 2010-09-16 14:53:55

+0

哈哈,对于同样的事情+1# – 2010-09-16 14:54:32

+0

似乎不工作...编译器显示错误:“期望”)'之前'<'token'in'typedef void(MyClass :: * type )( T param);“ (“(MyClass :: * type)(T param)”),错误出现在“void DelayedFunction(TFunc :: type func,T param,float time);” - “func”之前的“期望的”)“......我不明白错误的原因。 – brigadir 2010-09-17 14:38:04