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

独自空忆成欢 提交于 2019-11-27 15:59:35

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; };
jaggedSpire

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.

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; };

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; });

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.

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