c++ - 这应该模棱两可吗? (隐式转换)

标签 c++ standards casting

 struct A 
 {
     A(const A& src);
     A(const char* src);
 };
 struct B 
 {
     operator A();
     operator char*();
 };
 void test()  
 {
     B v;
     A s(v);
 }

EDG/Comeau 和 MSVC 允许代码,而 GCC 4.4.4、CLANG 和 BCC 拒绝它是模棱两可的。

一位 C++ 委员会成员(最初)这样回答:

It's not ambiguous; the A(const A&) constructor is better than the A(const char*) constructor. The const A& parameter binds directly to the result of the conversion function, so the conversion sequence is considered to be a user-defined conversion followed by an identity conversion (13.3.3.1.4p1). The const char* parameter is a user-defined conversion followed by a qualification conversion, so it's worse.

然后,他跟进了。

Actually, I was wrong. While it is true that the second conversion sequence in a user-defined conversion sequence is a tiebreaker, looking more closely at 13.3.3.2p3, the next-to-last bullet, reveals that this tiebreaker only applies if the two sequences contain the same user-defined conversion sequence, and that is not the case in this example. Because one constructor's conversion sequence uses B::operator A() and the other uses b::operator char*(), there's no tiebreaker between the two user-defined conversion sequences and they are ambiguous.

我的问题是这个。

13.3.3.2 p3 指出,

Two implicit conversion sequences of the same form are indistinguishable conversion sequences unless one of the following rules apply.

据我了解,关键字是“以下规则之一”。 这并不意味着声明“相同转换顺序”的项目符号 覆盖以上所有内容。我会认为“S1的排名更好 比 S2 的等级更适用吗?

最佳答案

是的,根据我对第 13.3.3.2 条的最佳解释,预期结果是歧义

将“B”类型的参数“v”与“A”的任一重载构造函数的参数匹配需要用户定义的转换。这两个序列都是转换等级的。

我的解释是适用于 $13.3.3.2 中的以下引用

[...]User-defined conversion sequence U1 is a better conversion sequence than another user-defined conversion sequence U2 if they contain the same user-defined conversion function or constructor and if the second standard conversion sequence of U1 is better than the second standard conversion sequence of U2.

这两者都调用了“B”类中的不同转换函数。因此,我认为第一个条件本身不满足,因此预期结果是歧义,因为没有一个转换序列比另一个更好。

关于c++ - 这应该模棱两可吗? (隐式转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4263748/

相关文章:

c++ - 消息队列C++配合Qt进行网络传输

c++ - 将视频帧数据移动到 GPU 的最有效方法是什么?

python - 大于/小于 Python 中的比较

我可以在 C 中将 0.16、0.32 等正确转换为整数(16、32 等)吗?

c# - 不明显的数组索引

C++ 宏不会替换所有值

c++ - Spirit Boost real_p 解析器行为异常

vba - 我应该在 VB6 中显式声明我的变量吗

c - 为什么没有在 C 中定义 char 的符号?

java - Android NDK 是否为通过套接字发送大 int[] 提供加速?