简体   繁体   中英

Floating point and integer ambiguity

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM