I have this code:
std::function<std::string&(std::string&)> change_str = [](std::string& str){
return (str = "Hello world!");
};
std::string s;
std::cout << change_str(s) << std::endl;
It does not compile, and say:
main.cpp:8:47: error: no viable conversion from '(lambda at main.cpp:8:60)' to 'std::function<std::string &(std::string &)>'
std::function<std::string&(std::string&)> change_str = [](std::string& str){
^ ~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/v1/functional:1448:5: note: candidate constructor not viable: no known conversion from '(lambda at main.cpp:8:60)' to 'nullptr_t' for 1st argument
function(nullptr_t) _NOEXCEPT : __f_(0) {}
^
/usr/include/c++/v1/functional:1449:5: note: candidate constructor not viable: no known conversion from '(lambda at main.cpp:8:60)' to 'const std::__1::function<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > &(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > &)> &' for 1st argument
function(const function&);
^
/usr/include/c++/v1/functional:1450:5: note: candidate constructor not viable: no known conversion from '(lambda at main.cpp:8:60)' to 'std::__1::function<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > &(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > &)> &&' for 1st argument
function(function&&) _NOEXCEPT;
^
/usr/include/c++/v1/functional:1454:41: note: candidate template ignored: disabled by 'enable_if' [with _Fp = (lambda at main.cpp:8:60)]
__callable<_Fp>::value &&
^
main.cpp:8:60: note: candidate function
std::function<std::string&(std::string&)> change_str = [](std::string& str){
^
1 error generated.
However if I change the declaration of std::function
to auto
, then it works:
auto change_str = ...
Why is the explicit type not working for lambda?
A lambda with no return type is auto
, and auto remove the external reference, so you are not returning string&
but just string
.
Just declare the functional as
std::function<std::string&(std::string&)> change_str =
[](std::string& str) -> string& ///<--- NOTE THIS
{
return (str = "Hello world!");
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With