如何在过载分辨率算法中确定歧义? [英] How is ambiguity determined in the overload resolution algorithm?
问题描述
我想了解重载解析方法。
为什么这样不明确:
void func(double,int,int,double){}
void func(int,double,double,double){}
void main
{
func(1,2,3,4);
}
但这不是?
void func(int,int,int,double){}
void func(int,double,double,double){}
void main()
{
func(1,2,3,4);
}
在第一种情况下,有2个精确的参数匹配和2个转换匹配和3次转化,而在第二种情况下,有3次完全匹配和1次转化与1次完全匹配和3次转化。
那么为什么一个模糊,一个不是?这里的逻辑是什么?
重载解析规则只定义所有匹配集合的部分顺序 - F1
不是比 F2
更好的匹配,它并不意味着 F2
是比 F1
更好的匹配。精确的部分顺序可以被看作是比较 k
维度中的两个点,其中参数数量 k
。让它在 k
-dim space - (x_1,x_2,...,x_k)中的点上定义此部分顺序。 (y_1,y_2,...,y_k),如果对于所有i,x_i <= y_i,并且x_j < y_j至少一个j
。这就是标准定义的候选非模板函数的部分顺序。
让我们看看你的例子:
void func(double,int,int,double){}
vvv vvv vvv
更好的等于
void func double,double){}
vvv vvv
更好等于
void func(int,int,int,double){}
vvv vvv vvv vvv
等于更好等于
void func(int,double,double,double){}
vvv
等于
现在,除了一个之外,第一个重载比第二个更好参数AND不会比第二个差。因此,没有歧义 - 部分顺序确实声明第一个更好。
(上面的描述不考虑函数模板。 a href =http://en.cppreference.com/w/cpp/language/overload_resolution =nofollow> cppreference )。
I'm trying to understand the overloading resolution method.
Why is this ambiguous:
void func(double, int, int, double) {}
void func(int, double, double, double) {}
void main()
{
func(1, 2, 3, 4);
}
but this isn't?
void func(int, int, int, double) {}
void func(int, double, double, double) {}
void main()
{
func(1, 2, 3, 4);
}
In the first case there are 2 exact parameters matches and 2 conversions against 1 exact match and 3 conversions, and in the second case there are 3 exact matches and 1 conversion against 1 exact matches and 3 conversions.
So why is one ambiguous and one is not? What is the logic here?
The overload resolution rules only define a partial order on the set of all matches - if an overload F1
is not a better match than F2
, it does not imply that F2
is a better match than F1
. The exact partial order can be thought of as comparing two points in k
dimensions, where the number of arguments is k
. Lets define this partial order on points in k
-dim space - (x_1, x_2,..., x_k) < (y_1, y_2,..., y_k) if x_i <= y_i for all i and x_j < y_j for at least one j
. This is exactly the partial order on candidate non-template functions defined by the standard.
Lets look at your examples :
void func(double, int, int, double) {}
vvv vvv vvv
better better equal
void func(int, double, double, double) {}
vvv vvv
better equal
So neither overload is strictly better than the other.
In your second example:
void func(int, int, int, double) {}
vvv vvv vvv vvv
equal better better equal
void func(int, double, double, double) {}
vvv
equal
Now, the first overload is better than the second in all but one argument AND is never worse than the second. Thus, there is no ambiguity - the partial order does indeed declare the first one better.
(The above description does not consider function templates. You can find more details at cppreference.)
这篇关于如何在过载分辨率算法中确定歧义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!