【发布时间】:2019-09-21 01:02:54
【问题描述】:
我有一个带有模板方法的类,并希望将其特化存储在容器中。我的问题是将专用模板方法指针转换为共享相同签名的同一类的非模板方法指针是否有效。考虑:
#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++ 成员函数指针还很陌生,我读过强制转换它们可能很危险,所以这就是我问的原因。
提前致谢。
【问题讨论】:
-
我在你的代码中看不到任何演员表!
-
@AKL 我以为
&S::method1<int>会隐式转换为Method,不是吗?对不起,如果不是 lmao。
标签: c++ templates member-function-pointers