指向非模板成员函数指针的模板成员函数指针

时间:2019-09-21 01:02:54

标签: c++ templates member-function-pointers

我有一个带有模板方法的类,并希望将其专业化存储在容器中。我的问题是将专用模板方法指针转换为共享相同签名的同一类的非模板方法指针是否有效。考虑:

#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 ++成员函数指针还很陌生,并且我读到强制转换它们很危险,所以这就是我要问的原因。

谢谢。

1 个答案:

答案 0 :(得分:3)

实例化具有不同类型的模板方法后,它将获得常规方法的所有属性:它成为具有地址,名称(包括用于实例化的类型)等的独特函数。因此,您的方法有效

相关问题