Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

lambda - Is a C++ is_lambda trait, purely implemented as a library, impossible?

I have a question regarding C++0x lambdas. In my code, it would be beneficial to know whether or not a given type is the type of a C++0x lambda expression. To give an example:

struct foobar
{
  void operator()()
  {
  }
};

auto lambda = []{};
typedef is_lambda < decltype(lambda) > ::type T; // T would be a true_type
typedef is_lambda < foobar > ::type T; // T would be a false_type

It is rather easy to distinguish lambda expressions from function and member function types. Functors are another matter.

The problem I see here is the definition of lambda expressions according to the upcoming C++0x standard; the only thing that must be defined is a public call operator. However, this is true for a functor as well; testing for the presence of the call operator is not enough for distinguishing lambda expressions from functors. Furthermore, if the operator of a functor is not present, a compiler error will occur, since SFINAE does not apply. When does this happen? The functor's call operator may be templated. So, such a code:

typedef decltype(&T::operator()) call_type;

will work for both lambda expressions and functors with non-templated call operator, and generate a compiler error for templated call operators.

I believe an is_lambda < > trait can only be created using intrinsic compiler features. Do you see a way how to implement this trait?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since evaluation of lambda results in creating closure object, there isn't any difference as soon as the object passed to a function or copied. And, frankly, I can't imagine a problem that would require to know whether an object came from lambda.

Edit. A standard even has a note in 5.1.2/2:

Note: a closure object behaves like a function object (20.8).—end note


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...