c++ - 当重载方法将模板类作为参数时会发生什么

标签 c++ templates overloading

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/

相关文章:

c++ - 如何在 C++ 中处理数组(在堆栈上声明)?

c++ - 使用目录的 C++ 程序中的 PlaySound

c++ - 模板的部分特化

c++ - 为什么在限定的依赖名称之前需要关键字 "typename",而不是在限定的独立名称之前?

java - Java中的方法重载

C++ File Input 3 ints在线阅读

c++ - 在 C++ 中打开常量是否合法?

c++ - typename 在这种情况下是什么意思

swift:为什么重载 "=="运算符时需要符合 equatable?

c++ - 调用不带对象参数的非静态成员函数