Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

C++ conditional operator type casting!

212 views
Skip to first unread message

itcecsa

unread,
Oct 6, 2010, 7:07:01 AM10/6/10
to
{ Please convert tabs to spaces before posting. TIA., -mod/aps }

is the following expression legal?

D d1;
int i = 3;
i = (i==3) ? d1 : i;

I define a class D which overload operator () to return double. this
is class D.

class D
{
public:
operator double() const
{
return 11.2;
}
};

in the example above, the conditional operator takes 2 operands, one
is of type D, one with type int. I assume it implicitly type cast the
second operand d1 to double. but for g++ on Red Hat it doesn't
compile. this is the error:
operands to ? : have different types.

any ideas why this happens?

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Jiang

unread,
Oct 6, 2010, 4:06:28 PM10/6/10
to
On Oct 6, 8:07 pm, itcecsa <itce...@gmail.com> wrote:
> { Please convert tabs to spaces before posting. TIA., -mod/aps }
>
> is the following expression legal?
>
> D d1;
> int i = 3;
> i = (i==3) ? d1 : i;
>
> I define a class D which overload operator () to return double. this
> is class D.
>
> class D
> {
> public:
> operator double() const
> {
> return 11.2;
> }
>
> };
>
> in the example above, the conditional operator takes 2 operands, one
> is of type D, one with type int. I assume it implicitly type cast the
> second operand d1 to double.


Yes, according to 5.6/p5 and 5.6/p3, the conversion is reasonable
since you already defined the conversion explicitly.

> but for g++ on Red Hat it doesn't
> compile. this is the error:
> operands to ? : have different types.
>
> any ideas why this happens?

Seems you are still using GCC 3.3 or 3.4. Try a new one (or even
old one, :-) ) if possible. You above code snippet is not
illegal in my mind.

Regards,

Jiang

0 new messages