【问题标题】:templated function pointer模板函数指针
【发布时间】:2010-09-16 14:50:03
【问题描述】:

我有一种方法可以为类调用延迟函数:

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

【问题讨论】:

  • 如果我错了,请纠正我(这种语法远非简单,我太懒了^Hbusy 无法检查自己),但不能将((*obj).*(func)) (value) 拼写为obj-&gt;*func(value) 吗?
  • @sbi: (obj-&gt;*func)(value) 准确地说。

标签: c++ templates pointers function


【解决方案1】:

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

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

并使用TFunc&lt;T&gt;::type(如果在从属上下文中,则以typename为前缀)只要您会使用TFunc&lt;T&gt;

【讨论】:

  • +1 比我快 36 秒! :)
  • 似乎不工作...编译器显示错误:“func'之前的预期)' before '&lt;' token" in "typedef void (MyClass::*type&lt;T&gt;)(T param);" I tried to remove &lt;T&gt; in the line ("(MyClass::*type)(T param)"), the error appears in "void DelayedFunction (TFunc&lt;T&gt;::type func, T param, float time);" - "expected )'...我不明白错误的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 2016-10-18
相关资源
最近更新 更多