Reputation: 26060
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?
Upvotes: 4
Views: 258
Reputation: 91270
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
Upvotes: 0
Reputation: 51475
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
Upvotes: 3