Search code examples
c++lambdac++14functor

Can any lambda expression be expressed as a (templated) struct


I am looking for a counterexample to disprove the claim that any lambda expression can be expressed as a (templated) struct. In other words, it is possible to write a source-to-source compiler that should be able lift every lambda expression out of any scope and express it as a templated functor class.

For example, as far as the end user is concerned, the following two are equivalent:

auto foo(int parm){
  ...
  auto f = [x,&y](int z) {..};
  ..
  return foo(parm);
}

can be expressed as

template<class X, class Y>
struct Closure {
  X x; Y y;
  auto operator()(int z) {..};  
};
auto foo(int parm) {
  ...
  auto f = Closure<decltype(x), decltype(y)&>{x,y};
  ...
  return f(parm);
}

Can this transformation always be done? If not, is there an example that can demonstrate this. Thanks!


Solution

  • The closure type of a lambda is a class type with an overloaded operator() ([expr.prim.lambda]/3). The transformation you describe is done every time a lambda expression is being dealt with - by the implementation.