PGupta
PGupta

Reputation: 215

How to pass float value to function taking double as reference value

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

Answers (4)

Ajay
Ajay

Reputation: 18411

Solution depends on what exactly example is doing.

  • Is it changing the value passed by reference? If yes, you cannot pass 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).
  • If it is not changing value, you can just add 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.
  • Making it function template may or may not work, and it entirely depends on what function is doing.

Upvotes: 0

J.N.
J.N.

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

DanDan
DanDan

Reputation: 10562

You can template it.

template<typename T>
void example (T &var)

Upvotes: 2

dario_ramos
dario_ramos

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

Related Questions