【发布时间】:2019-07-18 04:59:39
【问题描述】:
在下面的代码中,如果我使用std::vector 参数调用它,我希望它使用std::vector 版本的f(),但它使用第一个并抱怨std::to_string(const std::vector<T>&) 不存在。我对模板重载解析的理解是它应该使用“更专业”的版本。不知何故,我认为这不适用于这里,因为这是函数重载而不是模板重载。但它甚至没有使用正常的函数重载结果规则,否则它会抱怨对 f() 的模棱两可的调用。
#include <vector>
#include <string>
template<typename T>
std::string f(T&& member) {
return std::to_string(member);
}
template<typename T>
std::string f(const std::vector<T>& member) {
return std::to_string(member[0]);
}
int main() {
int a = 42;
printf("%s\n", f(a).c_str()); // OK
std::vector<int> b = { 42 };
printf("%s\n", f(b).c_str()); // ERROR: to_string doesn't have a std::vector overload
return 0;
}
我做错了什么?
【问题讨论】:
-
如果没有必要,重载解析宁愿不添加 cv-qualification。