gpt4 book ai didi

C++ - 不明确的重载模板解析/推导

转载 作者:行者123 更新时间:2023-11-27 22:35:20 26 4
gpt4 key购买 nike

运行以下代码片段,我没有收到任何错误,并且得到了预期的结果。但是,由于第二个模板实例化是不明确的 ( both type specifiers are references ),我担心这可能不是定义的行为。
这种行为(编译器实例化最具体的重载模板)是否得到保证?

#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 更专业的类型.更专业的类型被认为更适合重载解析。因此,您的代码会正常运行。

关于C++ - 不明确的重载模板解析/推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55151917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com