我有一些代码无法编译,如下所示。经过一番挖掘后,我发现了第 14.1 段注释 5,其中指出:
确定其类型时,模板参数上的顶级 cv 限定符将被忽略。
我的代码如下所示:
#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;
}
Run Code Online (Sandbox Code Playgroud)
它给出了这个编译错误:
Run Code Online (Sandbox Code Playgroud)In function 'int main()' error: call of overloaded 'Func(const Bar&)' is ambiguous
有人可以评论标准中这条规则背后的推理吗?
小智 6
您的代码的问题是函数调用不明确。const Bar & 可以匹配值或 const 引用。G++ 说:
xx.cpp:24: error: call of overloaded 'Func(const Bar&)' is ambiguous
Run Code Online (Sandbox Code Playgroud)
这与模板没有任何关系 - 如果您重载非模板函数,您会得到相同的错误。
正如人们一次又一次地告诉你的那样,你不会通过阅读标准来学习 C++。