C ++函数将重复参数绑定到curried函数 [英] C++ Function bind repeating arguments to curried function

查看:221
本文介绍了C ++函数将重复参数绑定到curried函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解curry和调用一个函数的概念,该函数将三个字符串连接起来,但是只传递两个字符串并使用第二个参数两次。

I am trying to understand the concept of currying and calling a function which concats three strings but by passing only two strings and using the second argument twice.

但是,当我这样做时,第二个参数不会被发送到函数,它打印出一个空字符串。

However when I do this, the second argument is not getting sent to the function at all and it prints out an empty string. Is it some really obvious mistake?

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;

}

这是下面的输出。不使用_2两次意味着第二个参数传递第二和第三。如果在其位置使用字符串,它的工作正常。

This is giving the below output. Doesnt using the _2 twice mean that second argument be passed for both second and third. If a use a string in its place its working fine.

推荐答案

复制字符串很贵。因为 std :: bind 认为占位符的值只使用一次,所以它执行 std :: move 在字符串。这是为每个参数,因此, b c 是一个移动,这意味着空字符串。

Copying strings is expensive. Since std::bind thinks that the values of the placeholders are only used once, it performs a std::move on the strings. This is done for each Parameter and as a consequence, either b or c is a moved, that means empty string.

您可以通过传递const引用的参数来明确说明您的意思:

You can change that behavior by explicitly saying what you mean, by passing the arguments by const-reference:

string concatthreestrings(string const& a,string const& b,string const& c)

现在,它应该工作。

这篇关于C ++函数将重复参数绑定到curried函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆