gpt4 book ai didi

c++ - 显式指定通用 lambda 的 operator() 模板参数是否合法?

转载 作者:可可西里 更新时间:2023-11-01 16:26:44 25 4
gpt4 key购买 nike

以下 C++ 代码是否符合标准?

#include <iostream>

int main()
{
[](auto v){ std::cout << v << std::endl; }.operator()<int>(42);
}

clang++ 3.8.0g++ 7.2.0 compile this code fine (编译器标志为 -std=c++14 -Wall -Wextra -Werror -pedantic-errors)。

最佳答案

这确实符合标准。该标准指定必须有一个成员operator(),并且它在其paramater-declaration-clause 中为每次出现的auto 提供一个模板参数。没有禁止明确提供这些内容的措辞。

行的底部:lambda 的调用运算符只是一个普通函数(模板,如果是通用的)。


供引用,相关标准条款:

The closure type for a non-generic lambda-expression has a public inline function call operator (16.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 (17.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 (11.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-declaration-clause by replacing each occurrence of auto in the decl-specifiers of the parameter-declaration-clause with the name of the corresponding invented template-parameter.

N4659 (C++17) 中的 8.1.5.1/3 [expr.prim.lambda.closure],强调我的。

关于c++ - 显式指定通用 lambda 的 operator() 模板参数是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49392738/

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