用类方法作为参数的c++模板
C++ Template with class method as parameter
是否可以将类方法作为参数传递给模板?例如:
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
在被调用前将被解引用
相关文章:
- .cpp和.h文件中的模板专用化声明
- C++模板来检查友元函数的存在
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 如何在c++中为模板函数实例创建快捷方式
- 使用C++中的模板和运算符重载执行矩阵运算
- 有人能分解一下这个c++模板的语法吗
- 如何在c++17中制作一个模板包装器/装饰器
- 模板化建造师专业化
- 调用专用模板时出错"no matching function for call to [...]"
- 模板元程序查找相似的连续类型名称
- 如何在C++20中创建模板别名的推导指南
- 没有名称的C++模板参数
- 具有重复类型的C++可变模板
- 如何将enable-if与模板参数和参数包一起使用
- 没有用于初始化C++中的变量模板的匹配构造函数