以类方法为参数的 C++ 模板

Jer*_*rry 4 c++ templates

是否可以将类方法作为参数传递给模板?例如:

template<typename T, void(T::*TFun)()>
void call(T* x) {
    x->TFun();
}

struct Y {
    void foo();
};

int main() {
    Y y;
    call<Y,&Y::foo>(&y);  // should be the equivalent of y.foo()
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试编译上述内容,我会得到:

main.cpp: In instantiation of void call(T*) [with T = Y; void (T::* TFun)() = &Y::foo]:
main.cpp:12:23:   required from here
main.cpp:4:5: error: struct Y has no member named TFun
     x->TFun();
     ^
Run Code Online (Sandbox Code Playgroud)

这可能吗,如果可能,语法是什么?

0x4*_*2D2 6

这不是您引用指向成员的指针的方式。您需要先取消引用它:

(x->*TFun)();
Run Code Online (Sandbox Code Playgroud)

我用括号来处理运算符优先级问题。TFun在调用之前将被取消引用。