У меня есть этот код:
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;
Он не компилируется и не говорит:
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.
Однако, если я изменяю объявление std::function
на auto
, то он работает:
auto change_str = ...
Почему явный тип не работает для лямбда?