且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

隐式类型转换 - 编译器错误

更新时间:2022-12-13 18:12:55

错误是三元运算符必须具有单个类型,并且您的表达式(1 = 1)? f():false 有两种类型 - f()有类型 TypesafeBool false 的类型为 bool 。你可以在他们之间转换,但Comeau不知道你想使用。要解决它,将三元组的一边转换为另一个的类型:(1 = 1)? Comeau在这里是正确的,因为对于观察者来说,结果应该采用什么类型是显而易见的,三元表达式需要有一个单独的类型,而不参考它使用的类型,并且它应该选择的类型是不明确的。


This question is related to this question. The following code compiles fine VC9 compiler but gives the error when compied with Comeau online. Can anybody tell me which one is correct and what is the meaning of the error?

error: ambiguous "?" operation: second operand of type "TypesafeBool" can be converted to third operand type "bool", and vice versa TypesafeBool b = (1==1) ? f() : false;

class TypesafeBool
{
private:
    bool m_bValue;
    struct Bool_ { 
        int m_nValue; 
    };
    typedef int Bool_::* bool_;
    inline bool_ True() const { return &Bool_::m_nValue; }
    inline bool_ False() const { return 0; }

public:
    TypesafeBool( const bool bValue ) : m_bValue( bValue ){}
    operator bool_() const { return m_bValue ? True() : False(); }
};

TypesafeBool f()
{
    return TypesafeBool(true);
}

int main()
{
    TypesafeBool b = (1==1) ? f() : false;
}

The error is that the ternary operator must have a single type, and your expression (1=1) ? f() : false has two types -- f() has type TypesafeBool and false has type bool. You can convert between them, but Comeau doesn't know which you want to use. To resolve it, cast one of the sides of the ternary to the type of the other: (1=1) ? f() : TypesafeBool(false).

Comeau is correct here, as while it's obvious to the observer what type the result should take, the ternary expression needs to have a single type on its own, without reference to what it's used in, and the type it should pick is ambiguous.