【问题标题】:Calling functions from a std::map从 std::map 调用函数
【发布时间】:2016-08-23 22:37:24
【问题描述】:

我正在尝试构建Object,它将作为我的函数的处理程序。为了解释原因,我将使用它来扫描用户输入,检查地图是否匹配。如果找到匹配项,我将调用该函数并将 user-inputed 行的其余部分复制到该函数;

class Object
{
public:
    Object(std::map<std::string, void(*)(const std::string&)> MAP)
        {/*...code...*/};
};

快速示例代码:

class Main
{
public:
    void testFunc(const std::string& A)
    {

    }

    void construct()
    {
        Object{
            std::map<std::string, void(*)(const std::string&)> {
                {"exit", [](const std::string &A){ exit(1); }},
                //{"test1", (void(Main::*)(const std::string&))&testFunc},
                //{"test2", [](const std::string &A){ testFunc(A); }},
                //{"test3", [this](const std::string &A){ testFunc(A); }},
                {"NULL", NULL}
            }
        };
    }
};

注释的行都不起作用,产生了不同的错误,但其他行成功并且没有运行时错误(嗯,NULL 会是,但我正在处理)。

我的问题是,我是否正确地想象了这个机制,如果没有,我应该只保存指针并稍后转换为函数吗?是否可以在仅在类范围内定义的对象内保存引用和调用函数(也可以从类内部进行调用)?

很多问题.. 我知道。但我以前从未见过这样的做法。所以我想这可能是有充分理由的。

因为我没有指明错误,here is a link;

【问题讨论】:

  • 考虑参考和std::function
  • testFunc 的类型是 void(Main::*)(std::string const&amp;),而不是 void(*)(std::string const&amp;)——差别很大。
  • 如果您可以将testFunc 声明为static,它将消除错误。
  • @ildjarn Opps,这是一个重写错误,已修复。
  • @areuz : 我不确定你在说什么你修好了......

标签: c++ casting function-pointers c++14


【解决方案1】:

static 成员函数与非成员函数的不同之处在于它们采用额外的隐式参数 - 类实例。 Main::testFunc 需要两个参数:Mainstd::string const&amp;。但是您的界面只允许一个参数。完成这项工作的唯一方法是创建函数将引用的全局 Main* - 这是一个非常脆弱的设计。

相反,您可以使用std::function&lt;void(std::string const&amp;)&gt; 使您的界面更加通用。这是 any 可调用的,它接受 std::string const&amp;,而不仅仅是指向函数的指针。这将允许您编写最后一个版本:

{"test3", [this](const std::string &A){ testFunc(A); }},

这可能是您最好的选择。

【讨论】:

  • “成员函数与非成员函数的不同之处在于它们采用额外的隐式参数” 非静态成员函数。 (对不起,迂腐。)
  • @BaummitAugen 这是 C++。有迂腐,有错误。
  • 谢谢 :) 还在习惯 C++。看起来它解决了我所有函数的问题,我喜欢它使用 Lambda。这样,它给了我 option 使用传递的参数,否则它超出范围。
猜你喜欢
  • 2015-07-18
  • 1970-01-01
  • 2015-08-09
  • 1970-01-01
  • 2016-12-29
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
  • 2012-09-25
相关资源
最近更新 更多