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

半世苍凉 提交于 2019-12-07 03:05:37

问题


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

回答1:


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 [...]




回答2:


Presumably you don't want to assign non-assignable non-lambda functions either, so you could use std::is_assignable.



来源:https://stackoverflow.com/questions/8481997/how-to-detect-whether-a-type-is-a-lambda-expression-at-compile-time

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