C++11 Change `auto` Lambda to a different Lambda?

拟墨画扇 提交于 2019-11-26 17:22:46

问题


Say I have the following variable containing a lambda:

auto a = [] { return true; };

And I want a to return false later on. Could I do something along the lines of this?

a = [] { return false; };

This syntax gives me the following errors:

binary '=' : no operator found which takes a right-hand operand of type 
'main::<lambda_a7185966f92d197a64e4878ceff8af4a>' (or there is no acceptable conversion)

IntelliSense: no operator "=" matches these operands
        operand types are: lambda []bool ()->bool = lambda []bool ()->bool

Is there any way to achieve something like this? I would like to change the auto variable to a different lambda. I'm relitively a beginner so I may be missing some knowledge about auto or lambdas. Thanks.


回答1:


Every lambda expression creates a new unique type, so the type of your first lambda is different from the type of your second (example). Additionally the copy-assignment operator of a lambda is defined as deleted (example) so you're doubly-unable to do this. For a similar effect, you can have a be a std::function object though it'll cost you some performance

std::function<bool()> a = [] { return true; };
a = [] { return false; };



回答2:


A Lambda may be converted to a function pointer using the unary + operator like so:

+[]{return true;}

so long as the capture group is empty and it doesn't have auto arguments.1

If you do this, you may assign different lambdas to the same variable as long as the lambdas all have the same signature.

In your case,

auto a = +[]{return true;};
a = +[]{return false;};

Live example on Coliru

would both compile and act as you expect.2 You may use the function pointers in the same way you would expect to use a lambda, since both will act as functors.


1. In C++14, you can declare lambdas with auto as the argument type, like [](auto t){}. These are generic lambdas, and have a templated operator(). Since a function pointer can't represent a templated function, the + trick won't work with generic lambdas.

2. Technically, you don't need the second + operator on the assignment. The lambda would convert to the function pointer type on assignment. I like the consistency, though.




回答3:


Each lambda has a different type so you cannot change it. You could use a std::function to hold an arbitrary callable object, that can be changed at will.

std::function <bool ()> a = [] { return true; };
a = [] { return false; };



回答4:


We may use retrospective call to convert lambda to std::function:

template<typename T>
struct memfun_type
{
  using type = void;
};

template<typename Ret, typename Class, typename... Args>
struct memfun_type<Ret(Class::*)(Args...) const>
{
  using type = std::function<Ret(Args...)>;
};

template<typename F>
typename memfun_type<decltype(&F::operator())>::type
FFL(F const &func)
{ // Function from lambda !
  return func;
}

After that we will be able to do (since 'a' is std::function type now ):

auto a = FFL([] { return false; });
a = FFL([] { return true; });



回答5:


Since C++17 you can have the std::function template parameter deduced thanks to Class template argument deduction. It even works with capturing lambdas:

int a = 24;

std::function f = [&a] (int p) { return p + a; };
f               = [&a] (int p) { return p - a; };
f               = []   (int p) { return p; };

This comes in handy with more complex signatures and even more with deduced return types.



来源:https://stackoverflow.com/questions/38621623/c11-change-auto-lambda-to-a-different-lambda

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!