简体   繁体   English

返回语句中的 Lambda 不能隐式转换为仿函数

[英]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:我的问题是:

  1. Why run1() is okay but run2() is not allowed?为什么 run1( run1()可以,但run2()是不允许的?
  2. Is there a constructor in the struct Functor that I can define in order to make run2() valid as it is?我可以定义 struct 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()
  1. As it is already mentioned in the comments, run2 requires two implicit user conversions, which is prohibited.正如评论中已经提到的, run2需要两次隐式用户转换,这是被禁止的。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM