B
benben
Given a class template Vector<>, I would like to overload operator +.
But I have a hard time deciding whether the return type should be
Vector<U> or Vector<V>, as in:
template <typename U, typename V>
Vector<U_or_V> operator+ (
const Vector<U>&,
const Vector<V>&);
Naturally, I would like U_or_V to be the type of (U() + V()), but,
pardon my limited knowledge, I have no idea how to achieve that.
Currently I am defaulting U_or_V just to U. But this has some subtle
implications. For example, the breach of the commutative law:
Vector<int> vi(0, 0, 0);
Vector<double> vd(1.1, 1.2, 1.3);
assert((vi + vd) == (vd + vi));
The above innocent code may not even compile depending on how operator==
is declared. If it did, it is again up to the details of operator== to
decide whether the assertion would succeed or fail. Ideally, both
addition expressions should give Vector<double> because (int() + double
()) is a double.
Any thought will be appreciated!
Ben
But I have a hard time deciding whether the return type should be
Vector<U> or Vector<V>, as in:
template <typename U, typename V>
Vector<U_or_V> operator+ (
const Vector<U>&,
const Vector<V>&);
Naturally, I would like U_or_V to be the type of (U() + V()), but,
pardon my limited knowledge, I have no idea how to achieve that.
Currently I am defaulting U_or_V just to U. But this has some subtle
implications. For example, the breach of the commutative law:
Vector<int> vi(0, 0, 0);
Vector<double> vd(1.1, 1.2, 1.3);
assert((vi + vd) == (vd + vi));
The above innocent code may not even compile depending on how operator==
is declared. If it did, it is again up to the details of operator== to
decide whether the assertion would succeed or fail. Ideally, both
addition expressions should give Vector<double> because (int() + double
()) is a double.
Any thought will be appreciated!
Ben