用类方法作为参数的c++模板

C++ Template with class method as parameter

本文关键字:c++ 模板 参数 类方法      更新时间:2023-10-16

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

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()
}

如果我尝试编译上面的代码,我得到:

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();
     ^

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

不是这样引用成员指针的。你需要先解除引用:

(x->*TFun)();

我使用括号来处理操作符优先级问题。TFun在被调用前将被解引用