gpt4 book ai didi

c++ - 为什么嵌套类型的基类不需要 `typename`?

转载 作者:行者123 更新时间:2023-12-02 01:52:33 28 4
gpt4 key购买 nike

我非常惊讶地发现,当依赖类型作为基类出现时,没有必要添加 typename:

struct B {};

struct wr
{ typedef B type; };

template<class T>
struct A : T::type
{};

int main()
{
A<wr> a;
(void)a;
}

为什么T::type前面不需要typename

最佳答案

Why isn't typename required in front of T::type?

因为你不能从值继承。您使用 typename 告诉编译器给定的嵌套标识符是一种类型,但对于继承来说,无论如何都必须是这种情况,因此您可以省略它 - 这就是为什么该语言为 提供了一个异常(exception)>typename - 基本说明符的规则。来自 cppreference (强调我的):

The typename disambiguator for dependent names

In a declaration or a definition of a template, including alias template, a name that is not a member of the current instantiation and is dependent on a template parameter is not considered to be a type unless the keyword typename is used or unless it was already established as a type name, e.g. with a typedef declaration or by being used to name a base class.

请注意,我们会得到更多可以省略 typename 的地方,请参阅 P0634 .

关于c++ - 为什么嵌套类型的基类不需要 `typename`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57883831/

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