gpt4 book ai didi

c++ - 函数重载中的隐式转换序列

转载 作者:太空狗 更新时间:2023-10-29 21:42:35 26 4
gpt4 key购买 nike

我不明白编译器是如何选择最佳候选者的。例如,让我们有以下代码:

int function(double, int, int){...}
int function(int, double, double){...}

如果第二个函数需要转换两个变量而第一个函数只需要转换一个变量,为什么不选择第一个?为什么会出现这种模棱两可的情况?

最佳答案

Why is this an ambiguous situation?

根据§13.3.3/1,

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICS i (F1) is not a worse conversion sequence than ICS i (F2), and then

— for some argument j, ICS j (F1) is a better conversion sequence than ICS j (F2), or, if not that,

— [...]

因此像 function(0., 0., 0.) 这样的调用是不明确的;两个重载都不比另一个更好。

考虑从函数调用中推导模板参数 - 如果模板参数 T 用于多个函数参数(如 T a, T b, T c)并且对于调用的两个参数被推导为 int,但对于第三个参数推导为 double,如果这真的导致成功推导 T=int ?

过载解决方案不计算更好的匹配并判定获胜者 - 这不够果断。

想象一个拼图游戏 - 如果一 block 拼图在两端填充得更好,而在另一端填充得更差,那么它真的能更好地匹配缺口吗?

关于c++ - 函数重载中的隐式转换序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25825867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com