c++ - C++ - 模棱两可的重载模板解析/演绎
问题描述
运行以下代码片段,我没有收到任何错误,并且得到了预期的结果。但是,由于第二个模板实例化是模棱两可的(两个类型说明符都是引用),我担心这可能不是定义的行为。
这种行为(编译器实例化最具体的重载模板)是否得到保证?
#include <algorithm>
#include <iostream>
#include <vector>
template<typename T>
void Print(const T& x)
{
std::cout << x << std::endl;
}
template<typename T>
void Print(const std::vector<T>& x)
{
for(auto it = x.begin(); it != x.end(); ++it)
{
std::cout << *it << " ";
}
std::cout << std::endl;
}
int main(int argc, char const *argv[])
{
std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Print(5); // 5
Print(v); // 0 1 2 3 4 5 6 7 8 9
return 0;
}
我不知道在哪里看所以一个很好的参考也非常感谢。
解决方案
const std::vector<T>& x
是比 更专业的类型const T& x
。更专业的类型被认为更适合重载解析。因此,您的代码的行为应该如此。
推荐阅读
- python-3.x - Python Reportlab 自动换行表
- mysql - Laravel - 获取多个 withCount() 的总和
- amazon-web-services - Redshift自动增量不起作用开始负数
- python - N维数组变成单个数组?
- python - 这个例子中的加号有什么作用?
- c - 与传感器 CCS 编译器的 I2C 通信
- python - Python - 函数循环(多次重复使用输出作为输入)
- google-app-engine - Google App Engine YAML 资源配置不起作用
- domain-driven-design - 如何对具有一对零或多关系的聚合进行建模
- visual-studio-code - 无法访问 Visual Studio Code 中的默认用户设置面板