Reputation: 11416
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());
}
};
Upvotes: 10
Views: 2696
Reputation:
Presumably you don't want to assign non-assignable non-lambda functions either, so you could use std::is_assignable
.
Upvotes: 6
Reputation: 131829
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 [...]
Upvotes: 12