简体   繁体   English

浮点和整数模糊度

[英]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, 实际上我希望它采用int64_tlong double ,所以我想要的是,

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

However if I do this and try Foo f = 1; 但是,如果我这样做并尝试Foo f = 1; the compiler complains about the conversion from int to Foo being ambiguous. 编译器抱怨从intFoo的转换是模糊的。 Ok, but if I change the first constructor to take a int32_t there is no such ambiguity. 好的,但是如果我改变第一个构造函数来获取int32_t就没有这种歧义。 Can anyone explain to me why this is the case. 任何人都可以向我解释为什么会这样。

The type of the 1 literal is int. 1文字的类型是int。 Either constructor is going to need a conversion, int to int64_t vs int to long double. 构造函数都需要转换,int到int64_t vs int到long double。 The compiler doesn't think either of them is preferable so it complains. 编译器认为它们中的任何一个都不是优选的,所以它会抱怨。 Solve it by adding a Foo(int) constructor. 通过添加Foo(int)构造函数来解决它。 Or casting the literal, like (int64_t)1. 或者转换文字,如(int64_t)1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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