C++ 初始化器列表中std::bind初始化中的std::函数

C++ 初始化器列表中std::bind初始化中的std::函数,c++,c++11,initializer-list,stdbind,reference-wrapper,C++,C++11,Initializer List,Stdbind,Reference Wrapper,我有一张行动地图,根据特定的选择 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; struct选项{ int-num; std::string-txt; 功能动作

我有一张行动地图,根据特定的选择

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;
struct选项{
int-num;
std::string-txt;
功能动作;
};
带参数(int&a,int&b)的void function_
{
a=3;b=4;
}
int参数1=1;
int参数2=3;
我想以新的初始值设定项列表方式初始化向量:

const std::vector<option> choices
{ 
    {
        1,
        "sometext",
        std::bind(&funct_with_params, std::ref(param1), std::ref(param2))
    },
}
const std::向量选择
{ 
{
1.
“sometext”,
std::bind(&funct_与_参数,std::ref(param1),std::ref(param2))
},
}
我无法在向量中获得函数工作所需的初始化,是否有方法以某种方式将
std::bind
传递给向量

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


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

问题是option中的action成员变量的类型是
std::function
,您正在使用不同的函数初始化option(
std::function
)。这是由于
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;
}
#包括
#包括
#包括
结构选项{
int-num;
std::string-txt;
功能动作;
};
带参数(int&a,int&b)的void function_{
a=3;b=4;
}
int main(){
int参数1=1;
int参数2=3;
//矢量填充
const std::向量选择{
{1,“sometext”,std::bind(带有参数的函数,std::ref(param1),std::ref(param2))}
};
//数组填充
常数std::数组选项2={
{1,“sometext”,std::bind(带有参数的函数,std::ref(param1),std::ref(param2))}
};
返回0;
}

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

I。你犯了什么错误?你想做什么?我猜
act\u with_params
实际上是
funct\u with_params
,但是你是如何和在哪里声明
param1
param2
?请提供一个编译器。我用CLAN,我认为这可能是编译器问题。C++的第一年,你把CPU归咎于搞乱。第二年,你把窃听归咎于编译器。第三年,它是标准图书馆。直到第四年后,你才开始怀疑你的代码有错误。这对我来说毫无意义。。。两个参数绑定后,函数为空。然而,您确实可以将它存储在
std::function
中,并使用另外两个参数调用它,这两个参数将被忽略。这是我之前评论的后续内容:这是。不幸的是,这样的回答是错误的:
std::function action
起作用,并且是OP所追求的。