CppQuiz 系列3

3. 参数匹配

#include <iostream>

void f(int) { std::cout << 1; }
void f(unsigned) { std::cout << 2; }

int main() {
  f(-2.5);
}

答案是:CE

在选择重载函数时,如果没有完全匹配的,就会通过转换选择一个次匹配的,转换的种类如表中所示,题中所给的转换是属于浮点到整形的转换。相比之下没有更好的,所以编译器不知道选择哪个重载函数,所以是ill-formed。

这里写图片描述

This overload is ambiguous. Why?

There are two viable functions for the call f(-2.5). For the compiler to select one, one of them needs to be better than the other, or the program is ill-formed. In our case, they are equally good, making the program ill-formed.

According to §13.3.3 in the standard, a viable one-argument function is better than another if the conversion sequence for the argument is better. So why isn’t the int conversion sequence better than the unsigned conversion sequence, given that the double is signed?

All conversions are given a rank, and both “double => int” and “double => unsigned int” are of type “floating-integral conversion”, which has rank “conversion”. See Table 12 in the standard and §4.9. Since they have the same rank, no conversion is better than the other, and the program is ill-formed.


接上期,题中一共列出了4种函数声明和两种参数形式,列表如下:

函数声明&参数类型const char []const char *
const std::string &ConversionConversion
const void *Array to pointerPointer Conversion
template T &sT=const char &[]T=const char * &
templateconst char (&)[N]Identity不匹配

可见,对于T&来说,对两种参数都是属于Exact Match,而偏特化版本对const char[] 是Identity,而对const char * 不匹配,结果一目了然,而const void * 和 const std::string & 都需要进行转换,所以,const char [] 匹配 const char (&)[N],const char * 匹配T&.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值