C ++: promotion of non-native types

Suppose I have a 2D vector template class:

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

I would expect the result of the sum between a Vec2<double> and a Vec2<int> be Vec2<double> , but C ++ will not do this by default.

Am I thinking wrong?
Should I try to implement this behavior?

And how do I implement this? One way may be overridden by any operator, so that the advanced type of computed using the auto and decltype or do it yourself, for example, to promote , but this way - it is anything but trivial and not even let me use boost.operators to facilitate my work . Other offers?

+4
source share
2 answers

I like the following:

 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

and

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

+3
source

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

You can create generic operators that are advertised on the basis of the basic type, or you can make explicit promotions for the cases you need, which is a safe IMO.

0
source

Source: https://habr.com/ru/post/1341606/


All Articles