gpt4 book ai didi

c++ - 不能使用显式类型的 lambda

转载 作者:可可西里 更新时间:2023-11-01 14:56:52 24 4
gpt4 key购买 nike

我有这个代码:

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 = ...

为什么显式类型不适用于 lambda?

最佳答案

没有返回类型的 lambda 是 auto,并自动删除外部引用,因此您不会返回 string& 而只是 string

只需将功能声明为

std::function<std::string&(std::string&)> change_str = 
[](std::string& str) -> string& ///<--- NOTE THIS
{
return (str = "Hello world!");
};

关于c++ - 不能使用显式类型的 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25899112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com