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

Why ( ? : ) Between an int and a float with operator float() resolves as int?

51 views
Skip to first unread message

Paolo Biagini

unread,
Apr 5, 2016, 7:38:46 AM4/5/16
to
see code...


#include <iostream>
#include <typeinfo>
using namespace std;

int main()
{
class fff
{
float val;
public:
explicit fff(float f) : val(f) {}
operator float() const { return val; }
float getfloat() const { return val; }
} f(42.42f);

auto foo1 = true ? 1 : f;
auto foo2 = true ? 1 : f.getfloat();
auto foo3 = true ? 1.1 : f;
auto foo4 = true ? 1.1 : f.getfloat();

cout << typeid(foo1).name(); // foo1 = int ???
cout << typeid(foo2).name(); // foo2 = float ok
cout << typeid(foo3).name(); // foo3 = double ok
cout << typeid(foo4).name(); // foo4 = double ok

float uffa = false ? 1 : f; // LOOK THIS !!!
cout << uffa;
return 0;
}

output is: ifdd42
while I expected: ffdd42.42
or better a compiler arror !!!

Alf P. Steinbach

unread,
Apr 5, 2016, 1:37:45 PM4/5/16
to
On 05.04.2016 14:01, Stefan Ram wrote:
> Paolo Biagini <paolo...@gmail.com> writes:
>> true ? 1 : f;
>
> 5.16p3
>
> |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 there is no implicit conversion from `int` to your class `fff`.

Cheers!,

- Alf

Öö Tiib

unread,
Apr 5, 2016, 6:31:47 PM4/5/16
to
On Tuesday, 5 April 2016 14:38:46 UTC+3, Paolo Biagini wrote:
> see code...

Implicit conversion operators, implicit conversion constructors,
operator overloading, 'auto' and 'std::initializer_list' are
ILLUSION school spells of C++ wizard. Sometimes carefully cast
illusion makes something to look bit nicer than it really is.

Wussies and weenies will self-confuse with those and run away, evil
sorcerers will confuse their colleagues and will be kicked out and
so only good engineers will be left in C++ teams. It will be bit
painful but that is the procedure. Hopefully you got the warning. ;)
0 new messages