简体   繁体   English

当参数不同时,重载分辨率不选择模板

[英]Overload resolution doesn't choose template when arguments are different

Why the third function call of f is not using the function template?为什么 f 的第三个函数调用没有使用函数模板?

#include <iostream>
using namespace std;

template<class T> void f(T x, T y) { cout << "Template" << endl; }

void f(int w, int z) { cout << "Non-template" << endl; }

int main() {
   f( 1 ,  2 );
   f('a', 'b');
   f( 1 , 'b');
}

Function template type deduction is very stringent.函数模板类型推导非常严格。 For each pair of function parameter and argument, deduction happens in isolation, and then deduction results are compared:对于每一对函数形参和实参,单独进行推导,然后比较推导结果:

[temp.deduct.type] [temp.deduct.type]

2 In some cases, the deduction is done using a single set of types P and A, in other cases, there will be a set of corresponding types P and A. Type deduction is done independently for each P/A pair, and the deduced template argument values are then combined.2在某些情况下,推导是使用一组类型 P 和 A 完成的,在其他情况下,会有一组对应的类型 P 和 A。对每个 P/A 对独立进行类型推导,推导的然后组合模板参数值。 If type deduction cannot be done for any P/A pair, or if for any pair the deduction leads to more than one possible set of deduced values, or if different pairs yield different deduced values, or if any template argument remains neither deduced nor explicitly specified, template argument deduction fails.如果不能对任何 P/A 对进行类型推导,或者如果对于任何一对推导导致多于一组可能的推导值,或者如果不同的对产生不同的推导值,或者如果任何模板参数既未推导也未显式指定,模板参数推导失败。

This means that the type of x is deduced from 1 (and int), and the type of y is deduced from 'b' (a char) as though the other parameter didn't exist.这意味着x的类型是从1 (和 int)推导出来的,而y的类型是从'b' (一个字符)推导出来的,就好像另一个参数不存在一样。 This deduction yields T = int and T = char separately, and since those are different types, deduction must explicitly fail per the above paragraph.这种推导分别产生T = intT = char ,并且由于它们是不同的类型,因此根据上述段落推导必须明确失败。

If you want to call an instantiated function, you must specify T explicitly yourself:如果调用实例化函数,则必须自己显式指定T

f<int>( 1 , 'b');
f<char>( 1 , 'b');

In the third call, the two arguments are of different types, so T cannot be deduced, and the template function is not viable.在第三次调用中,两个参数的类型不同,因此无法推导出T ,模板函数不可行。 The non-template one is then the only viable candidate.非模板是唯一可行的候选者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM