views:

51

answers:

1

I have a function (and a constructor) that should be able to take integer and floating point values. In fact I want it to take an int64_t or a long double, so what I want is,

class Foo {
    public:
    Foo(int64_t value=0);
    Foo(long double value);
};

However if I do this and try Foo f = 1; the compiler complains about the conversion from int to Foo being ambiguous. Ok, but if I change the first constructor to take a int32_t there is no such ambiguity. Can anyone explain to me why this is the case.

+5  A: 

The type of the 1 literal is int. Either constructor is going to need a conversion, int to int64_t vs int to long double. The compiler doesn't think either of them is preferable so it complains. Solve it by adding a Foo(int) constructor. Or casting the literal, like (int64_t)1.

Hans Passant
Ah yes, thankyou. Makes sense. I'm a little surprised that the compiler doesn't recognise an `int64_t` as a closer match to an `int` than a `double` is though. (I guess because a conversion is a conversion and that's all it worries about(?))
tjm