Don Pavilon
Don Pavilon

Reputation: 119

How to calculate the difference of two numbers in c++?

If I enable double and integer only, then it is 4 functions. But I want to enable all data types (int long float double unsigned numbers etc.) How is it possible?

#include <iostream>

using namespace std;

double diff(int num1, int num2) {
    return double(num1-num2);
}

double diff(int num1, double num2) {
    return double(num1)-num2;
}

double diff(double num1, int num2) {
    return num1-double(num2);
}

double diff(double num1, double num2) {
    return num1-num2;
}

int main() {
    int a = 10;
    double b = 4.4;
    cout << diff(a, b) << endl;
    return 0;
}

Upvotes: 8

Views: 4811

Answers (6)

Fred Foo
Fred Foo

Reputation: 363817

template <typename T, typename U>
double diff(T a, U b) {
    return a - b;
}

You don't need the cast to double -- this is done for you if either argument is a double, and during return when both are integers. However,

double diff(double a, double b);

can be called with int arguments as well.

Upvotes: 9

Crossman
Crossman

Reputation: 278

You could always calculate the difference using absolute values, for instance

cout << abs(a - b) << endl;

you might want to use templates like previous answers said though.

Upvotes: 1

fasked
fasked

Reputation: 3645

Unlike all of previous answers I would add about C++11. In C++11 you can use decltype.

#include <iostream>

template <typename T1, typename T2>
auto diff(T1 a, T2 b) -> decltype(a)
{
   return (a - b);
}

int main() {
   std::cout << diff(3.5, 1) << std::endl;
   std::cout << diff(3, 1.5) << std::endl;
}

diff function will always return value of type like first argument. Note in first case it is float number, but in second it is integer.

Upvotes: 3

juanchopanza
juanchopanza

Reputation: 227608

Use a template function:

template <typename T1, typename T2>
double diff(const T1& lhs, const T2& rhs)
{
  return lhs - rhs;
}

Upvotes: 8

ersran9
ersran9

Reputation: 978

You could define a template for the same

template <typename T, typename U>
T diff(const T& a, const U& b) {
    return a - b;
}

This code makes a lot of assumptions, like operator - is defined for T, and return type will be always of type T and so on...

Upvotes: 1

thedayofcondor
thedayofcondor

Reputation: 3876

You don't have to "enable" operations, just write:

cout << (a - b) << endl;

Upvotes: 4

Related Questions