使用 map cpp 创建成员变量

Create a member variable using map cpp

我正在尝试使用 std::map 键值对调用函数。我找到了这篇 Whosebug 文章 但解决方案

std::map<std::string, std::function<void()>> le_mapo;

不起作用并导致类似“错误:左值需要作为一元‘&’操作数”这样的错误

std::map<std::string, std::function<void()>> le_mapo;
le_mapo["ftp"] = &ftp(); // ftp function is in the same class, this function is the constructor

我正在尝试使用此方法在同一个 class 中调用一个函数,结果出现左值错误,不知道该怎么做

我也试过在顶部使用

#define BE_EVIL(map, function, x) map[ #x ] = & function ## x

注意:我有所有正确的包含,例如

#include <iostream>
#include <map>
#include <functional>

这是一个可重现的例子

#include <iostream>
#include <map>
#include <functional>


class Whosebug
{
    private:
        void ftp();
    
    public:
        Whosebug();
};

void ftp()
{
    std::cout << "Minimal reproduction" << std::endl;
}

Whosebug::Whosebug()
{
    std::map<std::string, std::function<void()>> le_mapo;
    le_mapo["ftp"] = &ftp();
}

因为 ftp 是一个成员函数,所以您将不得不使用 lambda here (well, you could use std::bind,但如今 lambda 表达式已在很大程度上取代了它。

所以你想要:

le_mapo["ftp"] = [this](){ ftp(); };

此“捕获”this,从而使您能够在正确的对象上调用 ftp()

&ftp() 不工作的原因有很多:

  • appending () 意味着你正在尝试调用该函数(然后获取它的地址 returns),而不是获取 [=11] 的地址=]直接。

  • 获取成员函数地址的语法是&Whosebug::ftp,而不仅仅是&ftp.

  • 您没有在任何地方传递 this,因此调用者将没有可调用 ftp 的对象。

这个:

le_mapo["ftp"] = &ftp();

是错误的,因为 ftp() 正在调用该函数,然后才应用寻址运算符。虽然你不能获取 void 的地址。函数指针是&Whosebug::ftp.

您需要一个对象来调用成员函数。 std::function 有一些魔力可以将成员函数转换为以对象为参数的可调用对象,因此它有效:

Whosebug::Whosebug()
{
    std::map<std::string, std::function<void(Whosebug&)>> le_mapo;
    le_mapo["ftp"] = &Whosebug::ftp;
}

调用映射中的函数时,您必须传递对 Whosebug 类型对象的引用,该对象将用于调用成员函数。

或者,您可以将对象与成员函数一起包装在 lambda 中,如其他答案所示。


PS:我想您的代码中有错字,因为:

void ftp()
{
    std::cout << "Minimal reproduction" << std::endl;
}

是一个与 Whosebug::ftp 完全无关的免费功能。当 ftp 是一个自由函数时,您不需要 lambda(其他答案)或带有附加参数的 std::function。对于免费功能,您 link 中的问答答案就是您所需要的。