01100110
01100110

Reputation: 2344

C++ Return double or int from function

I have a function that takes the exact same args, but sometimes I'd like for it to return a double and other times I'd like for it to return an int. What's the proper way to do that?

I could do function overloading, but the declarations of overloaded functions must differ from each other by the types and/or the number of arguments in the argument list. These would be identical so function overloading would not apply (I don't think).

double calc( int value, int add, double mult )
{
     // Sometimes I want this to return int. Sometimes double.
     return (value + add) * mult;
}

I'd rather not cast to int when that's the type I expect or write two functions (one for ints, the other for doubles). Thanks for any advice.

Upvotes: 1

Views: 19098

Answers (4)

user5411391
user5411391

Reputation: 11

just do it as a double or use a template and let the compiler figure it out.

If your int = 1 Then double = 1.0

They are the same number and double will help with the precision.

Just have it return a double. It uses more memory, but it's local scope so who cares?

Upvotes: 1

Adam Liss
Adam Liss

Reputation: 48300

You can create a second function:

int calcInt(int value, int add, double mult) {
  return calc(value, add, mult);
}

Or you can use a template:

template <class myType>
myType calc(int value, int add, myType mult) {
  return (value + add) * mult;
}

You can't create a different function with the same name and arguments; the compiler wouldn't know which one you wanted to invoke.

Upvotes: 5

Anteru
Anteru

Reputation: 19384

template <typename T, typename U>
T calc (const int value, const int add, const U mult)
{
    return static_cast<T> ((value + add) * mult);
}

calc<double> (1, 2, 1.7); // returns double
calc<int> (1, 2, 3.4); // returns int

Upvotes: 5

Dilum Ranatunga
Dilum Ranatunga

Reputation: 13374

Assuming this is for maintaining precision or something like that, I would define my own type -- Number or something like that, and manage whether it is an int or double internally.

Upvotes: 1

Related Questions