代码之家  ›  专栏  ›  技术社区  ›  brigadir

模板化函数指针

  •  3
  • brigadir  · 技术社区  · 15 年前

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

    //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 回复  |  直到 15 年前
        1
  •  10
  •   Alexandre C.    15 年前

    C++中没有模板类型DEFS。在C++ 0x中有这样的扩展。

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

    和使用 TFunc<T>::type (前缀为 typename 如果在一个依赖的上下文中)无论何时 TFunc<T> .