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.
With a Float object in Java we can use Float. doubleValue() method to return double value of it.
11 Answers. Show activity on this post. Yes.
Python programming language has many inbuilt libraries and functions. One among them is the float() function. With the help of the float() function, we can convert an input string or an integer value to a floating point value.
In C#, we know that Console. ReadLine() method is used to read string from the standard output device. Then this value is converted into the float type if it is not string type by default.
How about a template function?
template <typename T>
void example (T &var);
The compiler will replace both float
and double
usages (keep in mind C++ templates are macros with type-safety)
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:
void example(double& d);
double d = ...;
example(d); // unclear if d was modified
after:
double example(double d);
double d = ...;
d = example(d);
float f = ...;
f = static_cast<float>( example(f) ); // cast required to tell the compiler to allow
// the precision loss
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With