Uso Visual Studio 2008, así que tuve que crear una forma que no sea C++ 0x. Terminé haciendo algo como esto.
template<typename T> struct type_precedence { static const int value = -1; };
template< > struct type_precedence<long double> { static const int value = 0; };
template< > struct type_precedence<double> { static const int value = 1; };
template< > struct type_precedence<float> { static const int value = 2; };
template< > struct type_precedence<unsigned long long> { static const int value = 3; };
template< > struct type_precedence<long long> { static const int value = 4; };
template< > struct type_precedence<unsigned long> { static const int value = 5; };
template< > struct type_precedence<long> { static const int value = 6; };
template< > struct type_precedence<unsigned int> { static const int value = 7; };
template< > struct type_precedence<int> { static const int value = 8; };
template< > struct type_precedence<unsigned short> { static const int value = 9; };
template< > struct type_precedence<short> { static const int value = 10; };
template< > struct type_precedence<unsigned char> { static const int value = 11; };
template< > struct type_precedence<char> { static const int value = 12; };
template< > struct type_precedence<bool> { static const int value = 13; };
/////////////////////////////////////////////////////////////////////////////////////////
template<typename T, typename U, bool t_precedent = ((type_precedence<T>::value) <= (type_precedence<U>::value))>
struct precedent_type {
typedef T t;
};
template<typename T, typename U>
struct precedent_type<T,U,false> {
typedef U t;
};
/////////////////////////////////////////////////////////////////////////////////////////
template<typename T, typename U>
typename precedent_type<T,U>::t my_mul() { return T * U; }
EDITAR: Este es el ejemplo: de hecho, estoy haciendo esto para multiplicar vectores. Se ve algo como esto:
template<int N, typename T, typename U>
vec<N,typename precedent_type<T,U>::t> operator *(const vec<N,T>& v1,const vec<N,U>& v2) {
...
}
...
double3 = float3 * double3;
float4 = float4 * int4;
etc.
¿Es posible algo así sin C++ 0x? – Chris
@Chris: ¡Nopes! Esta función está disponible en MSVC++ [2010] y en g ++ (versión 4.3 y superior). –
no, esa es una de las razones por las que se han agregado elementos "automáticos" y "decltype" para solucionar este inconveniente que causaba problemas en áreas como programación genérica y tener que adivinar tipos complejos como iteradores de contenedor, etc. El operador no estándar "typeof" existía en algunos compiladores para soportar esto, pero ahora ha sido estandarizado para nuestro placer. – David