简体   繁体   English

为什么在 C++20 中的这种情况下仍然需要 `typename` 前缀?

[英]Why is `typename` prefix still required in such a case in C++20?

According to https://stackoverflow.com/a/61991146/508343 :根据https://stackoverflow.com/a/61991146/508343

One of the new features in C++20 is Down with typename . C++20 中的一项新功能是Down with typename

In C++17, you had to provide the typename keyword in nearly all† dependent contexts to disambiguate a type from a value.在 C++17 中,您必须在几乎所有 † 依赖上下文中提供 typename 关键字,以消除类型与值的歧义。 But in C++20, this rule is relaxed a lot.但在 C++20 中,这条规则放宽了很多。 In all contexts where you need to have a type, the typename keyword is no longer mandatory.在需要类型的所有上下文中,typename 关键字不再是必需的。

template<typename T>
concept IsOK = true;

template<typename T>
requires IsOK<T::U> // error: use ‘typename T::U’
void f()
{}

struct A
{
    using U = int;
};

int main()
{
    f<A>(); 
}

In the code above, obviously, IsOK concept can take types only.在上面的代码中,显然, IsOK概念只能采用类型。

Why is typename required here?为什么这里需要typename

See online demo在线演示

The answer is speaking loosely about what "context" means.答案是粗略地谈论“上下文”的含义。 What the feature is doing is finding places where it is grammatically impossible for anything other than a typename to appear in that location. 该功能所做的是找到在语法上不可能出现除类型名称以外的任何内容的位置。 It is those places where typename is no longer necessary.这是那些不再需要typename的地方。

For example, using name = X;例如, using name = X; . . Grammatically, this is a type alias declaration.从语法上讲,这是一个类型别名声明。 As such, whatever X is, the grammar requires that it be a type.因此,无论X是什么,语法都要求它是一个类型。 If the X happens to be a name dependent on a template parameter, whatever that name is must be a type.如果X恰好是一个依赖于模板参数的名称,那么无论该名称是什么,都必须是一个类型。 So the grammar is unambiguous, and typename is redundant.所以语法是明确的, typename是多余的。

The syntax name<X> states that X is a template argument to the template name .语法name<X>声明X是模板name的模板参数。 But template arguments do not have to be types.但模板 arguments 不必是类型。 A specific template may take a type as a specific argument, but grammatically , X could be an identifier referencing a variable or a template.特定模板可以将类型作为特定参数,但在语法上, X可以是引用变量或模板的标识符。 Therefore, you must disambiguate ambiguous dependent X s.因此,您必须消除不明确的依赖X的歧义。

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

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