简体   繁体   English

可以在 C++ 的模板参数列表中定义类型吗?

[英]Can a type be defined inside template parameter list in C++?

In the following definition of template struct B , a lambda is used as a default value of a non-type template argument, and in the body of the lambda some type A is defined:在模板struct B的以下定义中,使用 lambda 作为非类型模板参数的默认值,并且在 lambda 的主体中定义了一些类型A

template <auto = []{ struct A{}; }>
struct B {};

Clang and MSVC are fine with this definition, but GCC complains: Clang 和 MSVC 对这个定义很好,但 GCC 抱怨:

error: definition of ' struct<lambda()>::A ' inside template parameter list错误:' struct<lambda()>::A ' 在模板参数列表中的定义

Demo: https://gcc.godbolt.org/z/f1dxGbPvs演示: https://gcc.godbolt.org/z/f1dxGbPvs

Which compiler is right here?哪个编译器在这里?

[temp.param]/2 says: [temp.param]/2说:

Types shall not be defined in a template-parameter declaration.类型不应在模板参数声明中定义。

Taking this as written, GCC is correct to reject this code: this prohibition is not constrained to type-id of a type parameter, but applies to anywhere within template parameter declaration.鉴于此,GCC 拒绝此代码是正确的:此禁止不限于类型参数的类型 ID ,而是适用于模板参数声明中的任何地方。 Including nested within a lambda.包括嵌套在 lambda 内。

On the other hand, one might also read it as prohibiting lambdas themselves in template parameters.另一方面,也可以将其理解为在模板参数中禁止 lambda 本身。 After all, a lambda expression implicitly defines a class type ( [expr.prim.lambda.closure]/1 ).毕竟,lambda 表达式隐式定义了 class 类型( [expr.prim.lambda.closure]/1 )。

On the third hand, we also have [expr.prim.lambda.closure]/2 , which states:另一方面,我们也有[expr.prim.lambda.closure]/2 ,其中指出:

The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression .闭包类型在最小块 scope、class scope 中声明,或命名空间 Z31A1FD140BE4BEF2D11E121Z-表达式包含对应的lambda 表达式

The relevant scope here seems to be the namespace scope.这里相关的 scope 似乎是命名空间 scope。 This would imply the lambda should be treated as if its type were declared outside the template parameter list.这意味着 lambda 应被视为其类型在模板参数列表之外声明。 But then, so should be declarations inside the body of the lambda, and the definition in the question should be allowed.但是,lambda 体内的声明也应该如此,并且应该允许问题中的定义。

Personally, I consider it a defect in the standard that the scope of this prohibition seems so ill-defined.就个人而言,我认为这是标准中的缺陷,该禁令的 scope 似乎定义不清。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM