erikmc1
February 21st, 2008, 08:52 PM
Okay, I just found a solution using traits classes that define all of the type promotions in advance.
Thanks
-------------------------
Often I have the need to code a binary function that takes basic types, (e.g., an int and a double), and I'd like the return type to automatically be the highest promoted type using c++ type promotion rules. I've given an example below. Does anyone have a solution that would return a double for both calls, without requiring me to explicitly specify the return type, or without the need for explicit template specification for every combination of types?
Thanks in advance.
#include <iostream>
using namespace std;
// Intended to multiply basic types.
template <typename T, typename U>
T Multiply(T left, U right) {
return left * right;
}
// Generates compiler error if uncommented, since ambiguous, but we
// really want this to be a possible function as well.
/*
template <typename T, typename U>
U Multiply(T left, U right) {
return left * right;
}
*/
int main() {
int a = 5;
double b = 1.5;
// Good: returns a double.
cout << b << " * " << a << " = " << Multiply(b,a) << endl;
// Bad: returns an int and truncates the result.
cout << a << " * " << b << " = " << Multiply(a,b) << endl;
/* stdout:
1.5 * 5 = 7.5
5 * 1.5 = 7
*/
return 0;
}
Thanks
-------------------------
Often I have the need to code a binary function that takes basic types, (e.g., an int and a double), and I'd like the return type to automatically be the highest promoted type using c++ type promotion rules. I've given an example below. Does anyone have a solution that would return a double for both calls, without requiring me to explicitly specify the return type, or without the need for explicit template specification for every combination of types?
Thanks in advance.
#include <iostream>
using namespace std;
// Intended to multiply basic types.
template <typename T, typename U>
T Multiply(T left, U right) {
return left * right;
}
// Generates compiler error if uncommented, since ambiguous, but we
// really want this to be a possible function as well.
/*
template <typename T, typename U>
U Multiply(T left, U right) {
return left * right;
}
*/
int main() {
int a = 5;
double b = 1.5;
// Good: returns a double.
cout << b << " * " << a << " = " << Multiply(b,a) << endl;
// Bad: returns an int and truncates the result.
cout << a << " * " << b << " = " << Multiply(a,b) << endl;
/* stdout:
1.5 * 5 = 7.5
5 * 1.5 = 7
*/
return 0;
}