如何在编译时检测类型是否为lambda表达式? [英] How to detect whether a type is a lambda expression at compile time?
问题描述
假设我有一个my_struct
类型,其中包含一个成员变量f
,它是一个函数. f
可能是c ++ 11 lambda函数.
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.
由于分配给lambda对象是非法的,所以我想以my_struct
的赋值运算符实现这种方式,即当f
是lambda时,不对其进行分配.
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_lambda
来检查类型的lambda值?
Is it possible to build a type trait is_lambda
which can inspect a type for lambda-ness?
在代码中:
#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());
}
};
推荐答案
在没有编译器支持的情况下是不可能的,因为lambda的类型只是普通的非工会类类型.
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
lambda-expression 的类型(也是闭包对象的类型)是唯一的,未命名的ununion类类型[...]
The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed nonunion class type [...]
这篇关于如何在编译时检测类型是否为lambda表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!