为什么模板参数中的 cv 限定符被忽略?

4 c++ templates

我有一些代码无法编译,如下所示。经过一番挖掘后,我发现了第 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)

它给出了这个编译错误:

In function 'int main()'  
error: call of overloaded 'Func(const Bar&)' is ambiguous
Run Code Online (Sandbox Code Playgroud)

有人可以评论标准中这条规则背后的推理吗?

小智 6

您的代码的问题是函数调用不明确。const Bar & 可以匹配值或 const 引用。G++ 说:

xx.cpp:24: error: call of overloaded 'Func(const Bar&)' is ambiguous
Run Code Online (Sandbox Code Playgroud)

这与模板没有任何关系 - 如果您重载非模板函数,您会得到相同的错误。

正如人们一次又一次地告诉你的那样,你不会通过阅读标准来学习 C++。

  • @BE Student 从你在这里的帖子来看,你评估 C++ 编译器的资格就像我游过大西洋一样。正如我所指出的,您遇到的错误与模板没有特别关系。 (2认同)