如何将浮点值传递给以双精度作为参考值的函数
我有一个函数,其原型如下所示:
void example (double &var);
但是,我的问题是我可能还需要使用一些浮点值调用函数。 例如,
float temp=10.1;
example(temp)
如果我这样做,我的代码将无法编译,可能是因为将浮点值传递给双引用变量。
我想避免为 double 和 float 编写重载函数。
有人可以建议一个更干净/更好的方法来实现这个吗?
函数基本上是一个截断函数,它截断给定的输入 &是的,原来的已经修改了。
谢谢。
I have a function whose prototype looks like this:
void example (double &var);
But, my problem is I might require to call function with some float values as well.
e.g.
float temp=10.1;
example(temp)
If I do this my code don't compile, probably because of passing float value to double reference variable.
I want to avoid writing the overloaded function for double and float.
Can someone please suggest a cleaner/better way to implement this?
Function is basically a truncate function that truncate the input given & yes the original is modified.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
模板函数怎么样?
编译器将替换
float
和double
用法(请记住,C++ 模板是具有类型安全的宏)How about a template function?
The compiler will replace both
float
anddouble
usages (keep in mind C++ templates are macros with type-safety)不建议通过引用传递小类型。你最好有类似
double example(double var);
的东西。这也将解决你的问题。之前:
之后:
Passing small types by reference is not recommended. You'd better have something like
double example(double var);
. That will solve your problem as well.before:
after:
您可以将其模板化。
You can template it.
解决方案取决于
example
到底在做什么。float
传递给它。通过强制转换会编译,但会在运行时崩溃(因为您要传递 4 个字节,而需要 8 个字节)。void example (const double &var);
。如果可以进行转换(因为它现在被视为(double)
),编译器就不会抱怨。Solution depends on what exactly
example
is doing.float
to it. Passing by forceful conversion will compile, but would crash at runtime (since you'd be passing 4 bytes, where 8 bytes were needed).const
attribute to it, and pass any basic datatype. It would be:void example (const double &var);
. If conversion is possible (since it is now treated as(double)
), compiler wouldn't complain.