以下列例子为例:
#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.发布于 2016-09-07 19:57:15
g++6的行为是正确的,因为根据标准:
模板参数不应在其作用域(包括嵌套作用域)内重新声明。模板参数不应具有与模板名称相同的名称。
T的作用域在声明后立即开始,因此扩展到以下模板参数,该参数将T重新声明为模板参数,因此违反了此规则。
我认为g++5和g++6之间的变化是因为围绕类似的问题修复了一些bug报告。
https://stackoverflow.com/questions/39377928
复制相似问题