C++ 模版参数推断

C++模板参数推断是根据函数参数类型确定模板参数的过程。如果模板参数被用作多个函数参数类型,所有对应参数类型必须完全匹配。不匹配会导致错误。如果允许参数类型兼容,可以使用两个类型参数来定义模板。对于不匹配的类型,如数组或函数到指针的转换,编译器不会尝试匹配现有实例,而是生成新实例。特殊情况包括常量转换和数组或函数到指针的转换。
摘要由CSDN通过智能技术生成

16.2.1. Template Argument Deduction

To determine which functions to instantiate, thecompiler looks at each argument. If the corresponding parameter wasdeclared with a type that is a type parameter, then the compiler infersthe type of the parameter from the type of the argument. In the case of compare, both arguments have the same template type: they were eachdeclared using the type parameter T.

Inthe first call, compare(1, 0), those arguments are type int; in the second,compare, they have type double. The process of determining the types andvalues of the template arguments from the type of the function argumentsis called template argument deduction .

 

MultipleType Parameter Arguments Must Match Exactly

A template type parameter may be used as the type of more than one functionparameter. In such cases, template type deduction must generate the sametemplate argument type for each corresponding function argument. If thededuced types do not match, then the call is an error:


template <typename T>
int compare(const T& v1, const T& v2)
{
if (v1 < v2) return -1;
if (v2 < v1) return 1;
return 0;
}
int main()
{
short si;
// error: cannot instantiate compare(short, int)
// must be: compare(short, short) or
// compare(int, int)
compare(si, 1024);
return 0;
}


This call is in error because the arguments to comparedon't have the same type.The template argument deduced from the first ar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值