我有一些无法编译的代码,这相当于某种东西 如下图所示。经过一番挖掘,我发现了 第 14.1 段注释 5,其中指出:
The top-level cv-qualifiers on the template-parameter are ignored when determining its type.
我的代码是这样的:
#include <iostream>
#include <typeinfo>
class Bar {};
template<class T>
void Func(T t)
{
std::cout << typeid(T).name() << "\n";
}
template<class T>
void Func(const T& t)
{
std::cout << "const ref : " << typeid(T).name() << "\n";
}
int main()
{
Bar bar;
const Bar& constBar = bar;
Func(constBar);
return 0;
}
它给出了这个编译错误:
In function 'int main()' error: call of overloaded 'Func(const Bar&)' is ambiguous
有人可以评论一下标准中这条规则背后的原因吗?
最佳答案
您的代码的问题在于函数调用不明确。 const Bar & 可以匹配值或 const 引用。 G++ 说:
xx.cpp:24: error: call of overloaded 'Func(const Bar&)' is ambiguous
这与模板没有任何关系——如果你重载了一个非模板函数,你会得到同样的错误。
正如人们多次在这里告诉您的那样,您不会通过阅读标准来学习 C++。
关于c++ - 为什么忽略模板参数中的 cv 限定符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3361926/