1

如果我有类似的东西

class MyClass
{
public:
    void callMe()
    {
        cout << "called";
    }
};

template< void (MyClass::*callFunc)() > struct A 
{
   void A_call()
   {
       callFunc();
   }
};

int main(int argc, char *argv[])
{
   struct A <&MyClass::callMe> object;

   object.A_call();
}

这不会编译,因为它说“callFunc:术语不评估为采用 0 个参数的函数”。

类成员函数不是编译时常量吗?

4

3 回答 3

1

您已定义callFunc为指向成员函数的指针。要取消引用它(调用成员函数),您需要提供指针本身您要调用其成员的对象,沿着这条一般线:

template <void (MYClass::*callFunc)() > class A { 
    MyClass &c;
public:
    A(MyClass &m) : c(m) {}
    void A_call() { c.*callFunc(); }
};

int main() { 
    MyClass m;

    A<&MyClass::callMe> object(m);

    object.A_call();
};
于 2013-03-02T16:27:26.763 回答
0

You call the method callFunc() outside of the class MyClass and it is not static, then you will need an instance of MyClass to call it.

于 2013-03-02T16:25:16.840 回答
0
MyClass::callMe

is a non-static member function! You can't call it without an instance of MyClass! The instance is passed as first argument, therefor MyClass::callMe is actually:

void callMe(MyClass * this)

which obviously can't be called without an instance of MyClass...

于 2013-03-02T16:25:40.923 回答