Reputation: 215
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.
Upvotes: 5
Views: 6994
Reputation: 18411
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. Upvotes: 0
Reputation: 8421
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
Upvotes: 3
Reputation: 7309
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)
Upvotes: 5