How to multiply objects of different template type in C++ -
How to multiply objects of different template type in C++ -
how can create (with objects of different template types) a*b , b*a give same result, where type of result determined according usual c++ type promotion rules?
for example:
int main() { number<float> a(2.0f); number<double> b(3.0); a*b; // want 6.0 (double) b*a; // want 6.0 (double) homecoming 0; } at moment, can multiply objects of same template type. example, this:
template<typename t> class number { public: number(t v) : _value(v) {} t get_value() const { homecoming _value; } number& operator*=(const number& rhs) { _value *= rhs.get_value(); homecoming *this; } private: t _value; }; template<typename t> inline number<t> operator*(number<t> lhs, const number<t>& rhs) { lhs *= rhs; homecoming lhs; } edit: or, in answers, can multiply objects of different template types, always returning same type lhs. there way instead homecoming object type determined standard type promotion rules?
edit 2: i avoid c++11 features if possible.
you can utilize std::common_type<> obtain type required return. example
template<typename x> struct number { // ... template<typename y> number(number<y> const&other); // needed in line 1 below template<typename y> number&operator=(number<y> const&other); // may want template<typename y> number&operator*=(number<y> const&other); // needed in line 2 below template<typename y> number<typename std::common_type<x,y>::type> operator*(number<y> const&y) const { number<typename std::common_type<x,y>::type> result=x; // 1 homecoming result*=y; // 2 } }; i left out implementations of templated constructor , operator*=.
unfortunately, std::common_type c++11, want avoid obscure reasons. if work built-in types (double, float, int, etc), can implement own version of common_type. however, if want sophisticated meta-template programming, recommended move on c++11 – it's 4 years old , backwards compatible.
c++ templates operator-overloading
Comments
Post a Comment