Search code examples
c++c++11lambda

C++ lambda to std::function error with non const strings


The following line gives error in c++ 11:

function<bool(string,string)> comp = [] (string& s1, string& s2) {return s1.length() > s2.length(); };

but this does not:

function<bool(string,string)> comp = [] (const string& s1, const string& s2) {return s1.length() > s2.length(); };

The second call has const in parameters. Any explanation?


Solution

  • In your first case,

    function<bool(string,string)> comp = [] (string& s1, string& s2) {return s1.length() > s2.length(); };
    

    you are trying to compile something like this:

    bool comp(string& s1, string& s2){/*...*/}
    comp(string(), string());//passing a lvalue reference to a rvalue 
    

    The error here is you are trying to get a non-const lvalue reference to a rvalue, that's a violation of standard.

    Fixing solution 1, using function<bool(string &, string &)>(I think you probably trying to using this version):

    function<bool(string&,string&)> comp = [] (string& s1, string& s2) {return s1.length() > s2.length(); };
    

    Fixing solution 2, using rvalue reference:

    function<bool(string,string)> comp = [] (string&& s1, string&& s2) {return s1.length() > s2.length(); };
    

    In your second case,

    function<bool(string,string)> comp = [] (const string& s1, const string& s2) {return s1.length() > s2.length(); };
    

    you are trying to get a const lvalue reference to a rvalue, and this violates nothing of standard.