gpt4 book ai didi

c++ - 通用 lambda 在 C++14 中如何工作?

转载 作者:IT老高 更新时间:2023-10-28 11:53:17 25 4
gpt4 key购买 nike

通用 lambda 在 C++14 标准中如何工作(auto 关键字作为参数类型)?

它是基于 C++ 模板,其中每个不同的参数类型编译器生成一个具有相同主体但替换类型的新函数(编译时多态性)还是更类似于 Java 的泛型(类型删除)?

代码示例:

auto glambda = [](auto a) { return a; };

最佳答案

C++14 中引入了通用 lambda。

简单地说,由 lambda 表达式定义的闭包类型将有一个 templated 调用运算符,而不是 C++11 的常规、非模板调用运算符> 的 lambdas(当然,当 auto 在参数列表中至少出现一次时)。

所以你的例子:

auto glambda = [] (auto a) { return a; };

将使 glambda 成为这种类型的实例:

class /* unnamed */
{
public:
template<typename T>
T operator () (T a) const { return a; }
};

C++14 标准草案 n3690 的第 5.1.2/5 段规定了如何定义给定 lambda 表达式的闭包类型的调用运算符:

The closure type for a non-generic lambda-expression has a public inline function call operator (13.5.4) whose parameters and return type are described by the lambda-expression’s parameter-declaration-clause and trailing-return-type respectively. For a generic lambda, the closure type has a public inline function call operator member template (14.5.2) whose template-parameter-list consists of one invented type template-parameter for each occurrence of auto in the lambda’s parameter-declaration-clause, in order of appearance. The invented type template-parameter is a parameter pack if the corresponding parameter-declaration declares a function parameter pack (8.3.5). The return type and function parameters of the function call operator template are derived from the lambda-expression’s trailing-return-type and parameter-declarationclause by replacing each occurrence of auto in the decl-specifiers of the parameter-declaration-clause with the name of the corresponding invented template-parameter.

最后:

Is it similar to templates where for each different argument type compiler generates functions with the same body but changed types or is it more similar to Java's generics?

如上段所述,通用 lambda 只是具有模板化调用运算符的独特、未命名仿函数的语法糖。那应该回答你的问题:)

关于c++ - 通用 lambda 在 C++14 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17233547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com