我试图理解currying和调用一个函数的概念,该函数连接三个字符串,但只传递两个字符串并使用第二个参数两次.
但是,当我这样做时,第二个参数根本没有被发送到函数,它打印出一个空字符串.这是一个非常明显的错误吗?
string concatthreestrings(string a,string b,string c){
cout<<"Value of A: "<<a<<endl;
cout<<"Value of B: "<<b<<endl;
cout<<"Value of C: "<<c<<endl;
return a+b+c;
}
int main()
{
typedef std::function< string( string,string) > fun_t ;
using namespace std::placeholders;
fun_t fn = std::bind( concatthreestrings, _1, _2, _2);
cout<<endl<<fn( "First","Second")<<endl;
}
Run Code Online (Sandbox Code Playgroud)
这是给出以下输出.不使用_2两次意味着第二个参数将被传递给第二个和第三个.如果在其位置使用字符串,其工作正常.

复制字符串很昂贵.由于std::bind认为占位符的值仅使用一次,因此它对std::move字符串执行a .这是针对每个参数完成的,因此,移动b或c移动,这意味着空字符串.
您可以通过使用const-reference传递参数来明确说出您的意思来更改该行为:
string concatthreestrings(string const& a,string const& b,string const& c)
Run Code Online (Sandbox Code Playgroud)
现在,它应该工作.