首页 > 解决方案 > 模板成员函数指针指向非模板成员函数指针

问题描述

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

#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++templatesmember-function-pointers

解决方案


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


推荐阅读