visual 从映射C++中的功能指针调用函数

visual Calling a function from a funtion pointer in a map C++

本文关键字:功能 指针 调用 函数 映射 C++ visual      更新时间:2023-10-16

所以我不确定为什么这行不通,我尝试了一些谷歌搜索,我只是找不到问题是什么

void Player::Cmd(std::vector<std::string> &tokens)
{
std::string str = tokens[0];
std::map<std::string, void (Player::*)()>::iterator it = playerCommands.find(str);
Func fun;
if (it != playerCommands.end())
{
    fun = it->second; //i tried it->second(); same issue
    fun();  //error C2064: term does not evaluate to a 
            //function taking 0 arguments
}
else
{
    std::cout << "What? n";
}
}

项目的 Git 中心https://github.com/lordkuragari/TextRPG

你的看法相反,你的地图没有函数指针。因此,您无法调用映射中的元素。

相反,映射包含指向成员函数的指针。非静态成员函数不是函数,不能调用;相反,必须在对象上调用它们。您可以在指针p通过函数指针ptfm的对象上调用成员函数:

(p->*ptmf)();

在您的情况下,大概您想使用 p = thisptfm = fun ,所以它会是:

(this->*fun)();

或者,没有局部变量:

(this->*it->second)();

在 C++17 中,您还可以使用 std::invoke(it->second, this) .