Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect whether a type is a lambda expression at compile time?

Suppose I have a type my_struct enclosing a member variable, f, which is a function. It's possible for f to be a c++11 lambda function.

Since it is illegal to assign to lambda objects, I'd like to implement my_struct's assignment operator in such a way that when f is a lambda, it is not assigned.

Is it possible to build a type trait is_lambda which can inspect a type for lambda-ness?

In code:

#include <type_traits>

template<typename Function> struct is_lambda
{
  // what goes here?
};

template<typename Function> struct my_struct
{
  Function f;

  my_struct &do_assign(const my_struct &other, std::true_type)
  {
    // don't assign to f
    return *this;
  }

  my_struct &do_assign(const my_struct &other, std::false_type)
  {
    // do assign to f
    f = other.f;
    return *this;
  }

  my_struct &operator=(const my_struct &other)
  {
    return do_assign(other, typename is_lambda<Function>::type());
  }
};
like image 582
Jared Hoberock Avatar asked Dec 12 '11 22:12

Jared Hoberock


People also ask

How is lambda expression represented by JVM at runtime?

The bootstrap method information is needed for JVM to construct object representation of lambda during runtime. Lambda body code is generated within an instance or static private method which has the same parameters and return type as lambda's functional interface abstract method.

Are lambdas always Inlined?

All lambdas are inline. Not all calls to them are necessarily inlined.

Which is not a valid lambda expression?

Only A and B are valid.C is invalid because the lambda expression (Apple a) -> a. getWeight() has the signature (Apple) -> Integer, which is different than the signature of the method test defined in Predicate : (Apple) -> boolean.

Will lambda expression creates an object whenever it's executed?

Short answer: no.


1 Answers

Impossible without compiler support, as the type of a lambda is just a normal, non-union class type.

§5.1.2 [expr.prim.lambda] p3

The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed nonunion class type [...]

like image 127
Xeo Avatar answered Oct 01 '22 07:10

Xeo