模板函数指针 [英] templated function pointer
问题描述
我有一个方法来调用类的延迟函数:
//在MyClass声明:
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
virtual void operator()();
protected:
MyClass * obj;
IntFunc func;
int value;
};
//在MyClass.cpp文件中:
void MyClass :: DelayedFunction(IntFunc func,int value,float time)
{
TFunctorBase * functor = new TFunctorInt(this,func ,value);
DelayedFunctions.push_back(TDelayedFunction(functor,time)); //将在以后调用
}
void MyClass :: TFunctorInt :: operator()()
{
((* obj)。*(func)) );
}
我想创建模板函子。第一个问题是:
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
C ++中没有模板typedef。在C ++ 0x中有这样的扩展。同时,执行
模板< typename T>
struct TFunc
{
typedef void(MyClass :: * type)(T param);
};
并使用 TFunc< T> :: type
TFunc< T> 时,在<>之前加上 typename
I have an approach to call delayed function for class:
//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);
}
I want to make templated functor. And the first problem is that:
template <typename T>
typedef void (MyClass::*TFunc<T>) (T param);
Causes compiler error: "template declaration of 'typedef'". What may be a solution?
PS: The code based on http://www.coffeedev.net/c++-faq-lite/en/pointers-to-members.html#faq-33.5
There are no template typedefs in C++. There is such an extension in C++0x. In the meantime, do
template <typename T>
struct TFunc
{
typedef void (MyClass::*type)(T param);
};
and use TFunc<T>::type
(prefixed with typename
if in a dependant context) whenever you would have used TFunc<T>
.
这篇关于模板函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!