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

2019-01-12 08:39发布

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.

5条回答
Anthone
2楼-- · 2019-01-12 08:59

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; });
查看更多
Root(大扎)
3楼-- · 2019-01-12 09:01

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; };
查看更多
贪生不怕死
4楼-- · 2019-01-12 09:08

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.

查看更多
萌系小妹纸
5楼-- · 2019-01-12 09:12

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.

查看更多
ゆ 、 Hurt°
6楼-- · 2019-01-12 09:14

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; };
查看更多
登录 后发表回答