【发布时间】:2019-08-04 17:19:45
【问题描述】:
运行以下代码 sn-p,我没有收到任何错误,并且得到了预期的结果。但是,由于第二个模板实例化不明确(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;
}
我不知道在哪里看,所以也非常感谢一个好的参考。
【问题讨论】:
-
推论规则不容易遵循和理解,但你的代码表现得像它应该的那样。没什么好担心的。
-
来自cppreference
partial ordering selects ... as more specialized和Informally "A is more specialized than B" means "A accepts fewer types than B". -
谢谢大家。 @super 这正是我想要的!
标签: c++ c++11 templates language-lawyer type-deduction