C++: non-native types promotion

268 views Asked by At

Let's suppose I've got a 2D vector template class:

template<typename T> class Vec2 {
    T x, y;
    // ...
};

I'd expect that the result of a sum between a Vec2<double> and a Vec2<int> would be a Vec2<double>, but C++ won't do this by default.

Am I thinking in the wrong way?
Should I try and implement this behavior?

And how would I be supposed to implement that? One way could be overloading any operator so that the promoted type is computed using auto and decltype or some do it yourself type promotion, but this way is anything but trivial and wouldn't even allow me to use boost.operators in order to ease my work. Other suggestions?

2

There are 2 answers

0
Anycorn On BEST ANSWER

I do like this:

template<class V, class W>
struct vector_add;  

template<typename T, typename U, size_t N>
struct vector_add<Vec<T,N>, Vec<U,N> > {
    typedef BOOST_TYPEOF_TPL(T()+U()) value_type;
    typedef Vec<value_type, N> type;
};

http://www.boost.org/doc/libs/1_43_0/doc/html/typeof/refe.html#typeof.typo

also:

http://www.boost.org/doc/libs/1_46_0/libs/utility/operators.htm

0
Erik On

Vec2<double> and Vec2<int> are completely independent types that happened to be created from the same template. If you want any operation involving both of these to be possible, you need to implement it yourself.

You can create generic operators that promote based on the base type, or you could make explicit promotions for the cases you need, which is IMO safer