使用"A:<int>:template B x;"定义变量是否C++符合标准<int>?

Is it C++ standard-compliant to define a variable using `A<int>::template B<int> x;`?

本文关键字:int gt lt C++ 是否 标准 template 使用 定义 变量      更新时间:2023-10-16

下面的代码被gcc、vc++和clang接受。

template<class T>
struct A
{
    template<class U>
    struct B
    {};
};
int main()
{
    A<int>::B<int> y; // OK as expected
    A<int>::template B<int> x; // Also OK! Is this standard-compliant?
};

使用A<int>::template B<int> x;定义变量是否符合c++标准?

尽管这是一个非规范性的注释,我认为可以通过n3797[temp.names]/6给出答案

typename前缀的情况一样,template前缀在不是严格必要的情况下是允许的;即,当嵌套名称说明符->.左侧的表达式不依赖于模板参数,或使用不在模板范围内时。

在OP的示例中,前缀template在模板作用域之外使用,前面的嵌套名称说明符不是依赖的。因此,前缀template不是必需的,但在这里是允许的。


[expr.prim.general]/8

限定标识:
,,,,nested-name-specifier template opt   unqualified-id

+ [temp.names]/5

以关键字template为前缀的名称应该是模板id,或者该名称应该引用一个类模板。

[temp.names]/1说B<int>确实是一个(simple-)模板id