问题描述
泛型lambda如何在C ++ 14标准中工作( auto
关键字作为参数类型)
How does generic lambda work (auto
keyword as an argument type) in C++14 standard?
它是基于C ++模板,其中对于每个不同的参数类型编译器生成一个具有相同主体但替换类型(编译期多态性)的新函数,到Java的泛型(类型擦除)?
Is it based on C++ templates where for each different argument type compiler generates a new function with the same body but replaced types (compile-time polymorphism) or is it more similar to Java's generics (type erasure)?
代码示例:
auto glambda = [](auto a) { return a; };
推荐答案
通用lambdas介绍于 C ++ 14
。
Generic lambdas were introduced in C++14
.
简单地说,由lambda表达式定义的闭包类型将具有模板调用运算符,而不是常规的非模板调用操作符 C ++ 11
的lambdas(当然,当 auto
参数列表)。
Simply, the closure type defined by the lambda expression will have a templated call operator rather than the regular, non-template call operator of C++11
's lambdas (of course, when auto
appears at least once in the parameter list).
所以你的例子:
auto glambda = [] (auto a) { return a; };
会使 glambda
:
class /* unnamed */
{
public:
template<typename T>
T operator () (T a) const { return a; }
};
Paragraph 5.1.2/5 of the C++14 Standard Draft n3690 specifies how the call operator of the closure type of a given lambda expression is defined:
最后:
如上所述,通用lambdas只是用于具有模板调用操作符的唯一未命名函子的语法糖。这应该回答你的问题:)
As the above paragraph explains, generic lambdas are just syntactic sugar for unique, unnamed functors with a templated call operator. That should answer your question :)
这篇关于泛型lambda如何在C ++ 14中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!