Reputation: 119
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
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
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
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
Reputation: 227608
Use a template function:
template <typename T1, typename T2>
double diff(const T1& lhs, const T2& rhs)
{
return lhs - rhs;
}
Upvotes: 8
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
Reputation: 3876
You don't have to "enable" operations, just write:
cout << (a - b) << endl;
Upvotes: 4