Compiler error for conditional operator “?:” when used with typecasting operator

前端 未结 3 1281
囚心锁ツ
囚心锁ツ 2021-02-14 19:43

Following code is in simplest form:

struct X {
  operator char () const { return \'a\'; }
};

int main ()
{
  X obj, *p = &obj;
  char a = *p;  // ok
  char          


        
3条回答
  •  佛祖请我去吃肉
    2021-02-14 20:33

    It seems to be a compiler-bug. I checked it out in the spec, the Standard clearly says (§5.16/3 - C++03),

    Otherwise, if the second and third operand have different types, and either has (possibly cv-qualified) class type, an attempt is made to convert each of those operands to the type of the other.

    and the rest of the section explains how the conversion is done. There is nothing that stops *p from implicitly converting into char type, using the user-defined conversion operator.

    Also, I compiled it with (GCC) 4.5.0. It gives no error, with -pedantic option as well. Tried it -std=c++98 and -std=c++0x. Still no error.

    Most definitely, it is a compiler-bug.

提交回复
热议问题