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

标签 c++ templates

我有一些无法编译的代码,这相当于某种东西 如下图所示。经过一番挖掘,我发现了 第 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/

相关文章:

c++ - ZeroMQ dealer--to-dealer 与 winsock 相比延迟高

c++ - 位域和编译指示

c++ - 一个整数 [0,4095] 12 位元组 {A,B,C} 在 c++ 中最快的方法

c++ - 使用 PyInstaller 卡住 Python 脚本时包括 C++ 可执行文件

angularjs - 如何使用 webpack 编译 angular 模板?

c++ - 数组大小推导

c++ - 类中的指针/释放内存

c++ - 完全特化类模板的函数模板的显式特化

templates - 角度 cli Hook

c++ - 涉及 SFINAE 的重载 C++ 模板函数的地址