C++ 允许我们使用模板编写通用函数。并且它还具有函数重载的特性。
我编写了如下程序:
#include <iostream>
using namespace std;
template <typename T>
void test(T a)
{
cout<<"using template";
}
void test(int a)
{
cout<<"using int";
}
int main()
{
test(10);
return 0;
}
结果是:
using int
我想知道选择特定方法的依据是什么?
最佳答案
非模板函数比函数模板更匹配。
引用(C++ 草案标准 N3337):
13.3.3 Best viable function
...
Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then
...
— F1 is a non-template function and F2 is a function template specialization, or, if not that,
— F1 and F2 are function template specializations, and the function template for F1 is more specialized than the template for F2 according to the partial ordering rules described in 14.5.6.2.
关于c++ - 当重载方法将模板类作为参数时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26858076/