【问题标题】:std::function from std::bind initialization in the initializer liststd::function 来自初始化器列表中的 std::bind 初始化
【发布时间】:2017-01-20 09:40:23
【问题描述】:

我有一张针对特定选择要采取的行动的地图,

struct option {
  int num;
  std::string txt;
  std::function<void(void)> action;
};
void funct_with_params(int &a, int &b)
{
    a = 3; b = 4;
}
int param1 = 1;
int param2 = 3;

我想以新的初始化列表方式初始化那些向量:

const std::vector<option> choices
{ 
    {
        1,
        "sometext",
        std::bind(&funct_with_params, std::ref(param1), std::ref(param2))
    },
}

我无法在向量中进行初始化以使函数工作,是否有以某种方式将std::bind 传递给向量的方法?

我能够通过使用 lambda 表达式而不是绑定来使示例工作,我缺少什么吗?或者这不是std::bind的正确使用方式?

我正在使用 C++11,因为我无法迁移到更新的标准。

【问题讨论】:

  • can't reproduce your problem。你得到了什么错误?你想做什么?
  • 我猜act_with_params 实际上是funct_with_params,但是您是如何以及在哪里声明param1param2 的?请提供minimal reproducible example
  • 哪个编译器?
  • 我正在使用clang,我认为这可能是编译器问题。
  • C++ 的第一年,你责怪 CPU 搞砸了。第二年,你责怪编译器的错误。第三年,是标准库。只有在第四年之后,您才开始怀疑您的代码以某种方式出错。

标签: c++ c++11 initializer-list stdbind reference-wrapper


【解决方案1】:

问题是选项中的操作成员变量类型是std::function&lt;void(void)&gt;,而您正在使用不同的函数(std::function&lt;void(int &amp;a, int &amp;b)&gt;)初始化选项。这是由于 std::bind 正常运行 (std::bind)。

您需要正确的类型。另外我可能会建议,因为您想使用常量向量,所以最好使用std::array

代码示例:

#include <functional>
#include <vector>
#include <array>

struct option {
    int num;
    std::string txt;
    std::function<void(int &a, int &b)> action;
};

void funct_with_params(int &a, int &b){
    a = 3; b = 4;
}


int main(){
    int param1 = 1;
    int param2 = 3;

    //vector fill
    const std::vector<option> choices{
        { 1, "sometext", std::bind(funct_with_params, std::ref(param1), std::ref(param2)) }
    };

    //array fill
    const std::array<option, 1> choices2 = {
        { 1, "sometext", std::bind(funct_with_params, std::ref(param1), std::ref(param2)) }
    };
    return 0;
}

另一种解决方案是使用模板。

【讨论】:

  • 这对我来说毫无意义...一旦绑定了两个参数,该函数就为空。然而,您确实可以将其存储在 std::function&lt;void(int&amp;, int&amp;)&gt; 中并使用另外两个参数调用它,这些参数将被忽略。什么鬼。
  • 跟进我之前的评论:这是by design。不幸的是,这个答案是错误的:std::function&lt;void()&gt; action 有效并且是 OP 所追求的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-22
  • 1970-01-01
  • 2012-08-02
  • 1970-01-01
  • 2020-03-26
相关资源
最近更新 更多