【问题标题】:g++-6 errors on shadowed template parameters while g++-5 does not [duplicate]阴影模板参数上的 g++-6 错误,而 g++-5 没有 [重复]
【发布时间】:2017-01-15 14:50:41
【问题描述】:

举个例子:

#include <vector>

template <typename T, template <class T> class Container>
std::vector<T> To_Vector(Container<T> const& c){
  return std::vector<T>( c.begin(), c.end() );
}

int main(){}

使用g++-5,编译不会出错:

g++-5 -o main main.cpp 

g++-6 编译失败:

g++-6 -o main main.cpp
main.cpp:4:33: error: declaration of template parameter ‘T’ shadows template parameter
 template <typename T, template <class T> class Container>
                                 ^~~~~
main.cpp:4:11: note: template parameter ‘T’ declared here
 template <typename T, template <class T> class Container>

编译器错了吗?我的代码错了吗?
为什么g++-5 编译这段代码而g++-6 不编译?


g++-5 --version    
g++-5 (Ubuntu 5.4.1-2ubuntu1~14.04) 5.4.1 20160904
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

g++-6 --version
g++-6 (Ubuntu 6.2.0-3ubuntu11~14.04) 6.2.0 20160901
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

【问题讨论】:

  • @skypjack 好的,所以我应该省略 中的“T”,因为只有 为我构建。
  • 这是一个有效且有效的解决方案。 T 在您的示例中没有用,不是吗?
  • @skypjack 你是对的。我一定很困惑,认为容器类型名称必须专门用于类型 T,但这发生在实际参数上。
  • 是的,没错,函数的模板参数列表只提到了一个模板类,其参数列表的大小为1。在这种情况下,参数的名称是没有用的。

标签: c++ templates compiler-errors g++ shadow


【解决方案1】:

g++6 的行为是正确的,因为按照标准:

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

T 的作用域在其声明之后就开始了,所以它延伸到了下面的模板模板参数中,它将T 重新声明为模板参数,因此违反了这条规则。

我认为 g++5 和 g++6 之间的变化是由于修复了一些围绕类似问题的错误报告。

【讨论】:

  • 为什么这样可以代替? template &lt;template &lt;class T&gt; class Container, typename T&gt; 。它们是属于不同参数列表的不同范围吗?
  • @skypjack 第一个T 的作用域没有扩展到模板参数列表的其余部分,所以第二个T 没有隐藏它。
猜你喜欢
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-19
  • 2013-05-29
相关资源
最近更新 更多