【问题标题】:Is a typedef to self allowed over template parameters [duplicate]是否允许在模板参数上使用 typedef [重复]
【发布时间】:2021-09-22 02:30:30
【问题描述】:

当我看到这篇文章时,我正在阅读别人的代码(剥离到 MWE):

template<typename R> class Test {
    public:
        typedef R R;
};

这里有一个模板参数typedef给自己,它让GCC和clang(有或没有-std=c++2a)抱怨:

test.cc:3:19: 错误:'typedef R Test::R' 阴影模板参数的声明

但是,Compiler Explorer 上的 ICC 和 MSVC 都接受该片段。

我读过this question,建议给self 一个typedef 通常是无操作的。但是,这里似乎并非如此。我还发现 this question 是相关的,但我认为它们应该不同,因为我们在这里使用的是 typedef

所以问题来了:
标准允许这种重新定义吗? 该声明有任何副作用吗?为什么有人会这样写?

【问题讨论】:

标签: c++ templates language-lawyer typedef noop


【解决方案1】:

没有。模板参数名不能为redeclared

模板参数的名称不允许重新声明 在其范围内(包括嵌套范围)。模板参数是 不允许与模板名称同名。

template<class T, int N>
class Y {
    int T;                 // error: template parameter redeclared
    void f()
    {
        char T;            // error: template parameter redeclared
    }
};
 
template<class X> class X; // error: template parameter redeclared

来自标准,[temp.local]/6

模板参数的名称不应与以下任何内容绑定 模板参数的范围所包含的声明 属于。 [示例 5:

template<class T, int i> class Y {
  int T;                                // error: template-parameter hidden
  void f() {
    char T;                             // error: template-parameter hidden
  }
  friend void T();                      // OK: no name bound
};

template<class X> class X;              // error: hidden by template-parameter

——结束示例]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-15
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多