无法调用存储在 unordered_map 中的函数

Cannot call function stored in unordered_map

我试图让 call_function 接受一个字符串参数并调用映射中对应于该字符串的函数,但出现错误。我该如何解决?为什么不起作用?

#include <iostream>
#include <unordered_map>

using namespace std;

class xyz {
public:
    unordered_map< std::string, void(xyz::*)()> arr{
        { "user", &xyz::func_user},
        { "pwd", &xyz::func_pwd},
        { "dir", &xyz::func_dir}
    };

    void call_function(std::string x) {
        arr.at( x)();// Error: term does not evaluate a function taking 0 arguments
    }

    void func_user(){
        cout << "func_user" << endl;
    }

    void func_pwd(){
        cout << "func_pwd" << endl;
    }

    void func_dir(){
        cout << "func_dir" << endl;
    }

};

int main(){
    xyz a;

    a.call_function( "dir");
}

arr中的值是指向classxyz的非静态成员函数的指针,所以为了调用它们,你需要一个xyz对象。

直接调用成员函数时,通常可以省略this->。但是,当您通过指向成员的指针调用时,您不能省略 this->*。你必须明确地写它:

(this->*arr.at(x))();