[英]Lambda in return statement cannot be implicitly converted to functor
I have the following code我有以下代码
struct Functor
{
Functor(std::function<void()> task) : _task {task} {}
void operator() () {_task();}
std::function<void()> _task{};
};
Functor run1() //OK
{
return Functor([](){std::cout << "From function" << std::endl;});
}
Functor run2() //Bad. Compile time error
{
return [](){std::cout << "From function" << std::endl;};
}
My questions are:我的问题是:
run1()
is okay but run2()
is not allowed?run1()
可以,但run2()
是不允许的?Functor
that I can define in order to make run2()
valid as it is?Functor
中的构造函数以使run2()
有效吗? I am asking this because currently the return type of run2()
in my project is std::function<void()>
and all is good, but I now need to change it into a functor to store some additional properties, but return statement like run2()
are used in many places, and I am reluctant to modify every occurrences of it into run1()
.run2()
的返回类型是std::function<void()>
并且一切都很好,但是我现在需要将它更改为一个仿函数来存储一些额外的属性,但是返回语句像run2()
在很多地方都使用过,我不愿意将它的每一次出现都修改为run1()
。As it is already mentioned in the comments, run2
requires two implicit user conversions, which is prohibited.正如评论中已经提到的,
run2
需要两次隐式用户转换,这是被禁止的。
You can create a template constructor in Functor
to make your code valid:您可以在
Functor
中创建模板构造函数以使您的代码有效:
#include <functional>
#include <iostream>
struct Functor {
Functor(auto && task) : _task { task } {}
void operator() () {_task();}
std::function<void()> _task{};
};
Functor run1() //OK
{
return Functor([](){std::cout << "From function" << std::endl;});
}
Functor run2() //Ok
{
return [](){std::cout << "From function" << std::endl;};
}
Demo: https://gcc.godbolt.org/z/bdnYTbKv4演示: https://gcc.godbolt.org/z/bdnYTbKv4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.