c++ - 模板成员函数指针指向非模板成员函数指针
问题描述
我有一个带有模板方法的类,并希望将其特化存储在容器中。我的问题是将专用模板方法指针转换为共享相同签名的同一类的非模板方法指针是否有效。考虑:
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
struct S {
using Method = void(S::*)();
template <typename T>
void method1() {
cout << "method1(): " << T() << endl;
}
template <typename T, typename U>
void method2() {
cout << "method2(): " << T() << ", " << U() << endl;
}
void call(string name)
{
auto method_pair = methods.find(name);
if (method_pair == methods.end()) {
cout << name << " not found" << endl;
return;
}
Method& method = method_pair->second;
(this->*method)();
}
unordered_map<string, Method> methods;
};
int main()
{
S s;
s.methods["method_int"] = &S::method1<int>;
s.methods["method_bool"] = &S::method1<bool>;
s.methods["method_int_int"] = &S::method2<int, int>;
s.methods["method_bool_int"] = &S::method2<bool, int>;
cout << boolalpha;
s.call("method_int");
s.call("method_bool");
s.call("method_int_int");
s.call("method_bool_int");
s.call("nonexistant");
return 0;
}
输出:
method1(): 0
method1(): false
method2(): 0, 0
method2(): false, 0
nonexistant not found
上面的代码编译并运行得很好,我的设置没有警告。我对 C++ 成员函数指针还很陌生,而且我读过强制转换它们可能很危险,所以这就是我要问的原因。
提前致谢。
解决方案
在您实例化具有不同类型的模板方法后,它会获得常规方法的所有属性:它变成具有地址、名称(包括您用于实例化的类型)等的不同函数。因此您的方法是有效的。
推荐阅读
- c# - UWP C# - 为什么 NotifyPropertyChanged 在这种情况下不触发?
- c++ - 实现 pimpl 友好的 unique_ptr
- python - 如何从多对多表中检索字段?
- c# - 未注册的服务“Microsoft.EntityFrameworkCore.DbContext”
- javascript - 对下拉菜单进行更改,等待触发事件,然后进行更多更改
- linux - 删除 `~/my_repo/~` 中的 `~`
- php - MySQL根据表列中的值返回不同的字符串
- swift - Swift firebase 通过字符串数组查询数据
- android - “gradle”和“gradle plugin”有什么区别?
- linux - 仅使用 GNU sed 在第一次匹配时插入问题