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?Functor
that I can define in order to make run2()
valid as it is? 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()
.The characteristics of lambda functions are: Lambda functions are syntactically restricted to return a single expression. You can use them as an anonymous function inside other functions. The lambda functions do not need a return statement, they always return a single expression.
The return type for a lambda is specified using a C++ feature named 'trailing return type'. This specification is optional. Without the trailing return type, the return type of the underlying function is effectively 'auto', and it is deduced from the type of the expressions in the body's return statements.
What is the correct statement about lambda expression? Explanation: Return type in lambda expression can be ignored in some cases as the compiler will itself figure that out but not in all cases. Lambda expression is used to define small functions, not large functions.
What is the return type of lambda expression? Explanation: Lambda expression enables us to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button.
As it is already mentioned in the comments, run2
requires two implicit user conversions, which is prohibited.
You can create a template constructor in Functor
to make your code valid:
#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
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