c++ - 模板化函数指针

标签 c++ templates pointers function

我有一个为类调用延迟函数的方法:

//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

最佳答案

C++ 中没有模板类型定义。 C++0x中就有这样的扩展。与此同时,做

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

并使用TFunc<T>::type (如果在从属上下文中,前缀为 typename)每当您使用 TFunc<T> 时.

关于c++ - 模板化函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3727858/

相关文章:

c++ - 将一个数组值指向同一数组的另一个值 - C++

c++ - 删除指向 B 类型指针的 A 类型指针

python - 是否可以获得列表成员的指针?

c++ - Qt 排队连接中的槽调用顺序

python - 非结构化点云的区域增长 : failed verification pcl

c++ - 使用不同的起始定界符分割字符串(不重复)

c++ - 如何编写可以获取 QString 或 std::string 的子字符串的模板函数?

c++ - Qt 框架适用于此 Windows 和 Mac GUI?

c++ value_type 不适用于 std::map 中的 std::tr1:tuple

基于 C++ 模板的 get()