C++ 相关名称 : Is this typename required?

标签 c++ templates language-lawyer dependent-name

a.hpp中我定义了:

#include <utility>
namespace Board {
    template<int W, int H>
    struct GroupNode
    {
        using PointType = std::pair<int, int>;
        // ...
    };
}

然后,在b.cpp中我定义了:

#include "a.hpp"
namespace Board {
    template<int W, int H>
    struct NodeList
    {
        using StdList = std::list < /* typename */ GroupNode<W, H>>;
    }
}
// and then use NodeList<19, 19> nl;

上面的代码可以在没有任何警告的情况下在 gcc-6 和 clang-3.9 上编译。 但是,Clion 2016.3 提示 cannot resolve variable GroupNode in b.cpp。取消注释 typename 可以驯服 Clion 警告,但我想知道这个 typename 是否是必需的?如果是这样,为什么 g++/clang++ 没有发出任何警告?

最佳答案

不,这不是必需的。根据 C++14 中的 [temp.res]/3:

When a qualified-id is intended to refer to a type that is not a member of the current instantiation (14.6.2.1) and its nested-name-specifier refers to a dependent type, it shall be prefixed by the keyword typename, forming a typename-specifier . If the qualified-id in a typename-specifier does not denote a type, the program is ill- formed.

这里没有 nested-name-specifier 引用依赖类型,所以 typename 不是必需的。 (nested-name-specifier 指的是 :: 及其左侧的类型或命名空间。显然,std 不是类型,很多较少依赖类型。)

关于C++ 相关名称 : Is this typename required?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40756681/

相关文章:

c++ - 我应该什么时候通过 T const& 返回?

c++ - 模板特化中的隐式转换

c++ - consteval 函数是否允许依赖于函数参数的模板参数?

c++ - 变量在 C++ 中如何以及在哪里可能没有关联的名称?

c++ - 模板特化问题

C++ 跨平台包含破折号

c++ - 定义类型的宏

c++ - 如何在 C++ 中捕获整数溢出?

c++ - 不能引用派生模板类中的基类成员

c++ - 将可能的左值引用模板转换为左值