今天,我遇到了两个以前从未见过的错误消息。这对我来说是全新的。
代码如下:
template<typename T>
struct adder { adder(const T &item) { } };
template<typename T>
void initializer(const T &item) { adder<T>(item); }
int main()
{
initializer("const string literal");
}
在编译时,GCC 给出了这些错误:
prog.cpp: In function ‘void initializer(const T&)’:
prog.cpp:6: error: declaration of ‘adder<T> item’ shadows a parameter
prog.cpp: In function ‘void initializer(const T&) [with T = char [21]]’:
prog.cpp:10: instantiated from here
prog.cpp:6: error: declaration of ‘adder<char [21]> item’ shadows a parameter
prog.cpp:6: error: no matching function for call to ‘adder<char [21]>::adder()’
prog.cpp:3: note: candidates are: adder<T>::adder(const T&) [with T = char [21]]
prog.cpp:3: note: adder<char [21]>::adder(const adder<char [21]>&)
请参阅粗体文本。一个错误显示两次,就是这个
error: declaration of ‘adder<T> item’ shadows a parameter
error: declaration of ‘adder<char [21]> item’ shadows a parameter
这是什么意思?为什么使用不同的模板参数显示两次?第一个 T
, 第二个 char [21]
?
编辑:adder<T>(item)
用名称 item 声明变量?但这不是我想要的。我认为它应该创建一个临时对象,将 item 作为参数传递给构造函数。
我想知道标准中处理这个问题的部分!
另一个有趣的错误是:
error: no matching function for call to ‘adder<char [21]>::adder()’
这表明编译器正在寻找默认构造函数?但我想知道为什么编译器要查找它,而实际上我的代码并未在第 6 行使用它?
ideone 的代码:http://www.ideone.com/jrdLL
最佳答案
Which indicates that the compiler is looking for default constructor? But I'm wondering why is the compiler looking for it when in fact my code doesn't use it at line 6?
因为编译器认为您声明了名称为 item 的局部变量。
关于c++ - GCC的两个异常错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5297763/