I have a template class that depends on one type (e.g. template <typename T> class Vector). Now I want to overload arithmetic operators such that:
- I can use them with vectors created by two different types:
- The result is displayed in the same way as the types of template instances:
Example:
Vector<float> fv = {1.5, 2.5};
Vector<int> iv = {1,2};
auto s1 = fv + iv;
auto s2 = iv + fv;
I think that in a universal mathematical library that implements matrices, vectors, polynomials, etc., this will be a feature that makes a difference in terms of usability.
I found three ways to get this result using C ++ 11
-> designation
template <typename T, typename U>
auto operator +(const Vector<T> &lhs, const Vector<U> &rhs)
-> Vector<decltype(lhs[0]+rhs[0])>
{
Vector<decltype(lhs[0]+rhs[0])> res(lhs);
res += rhs;
return res;
}
declval
template <typename T, typename U>
Vector<decltype(std::declval<T>()+std::declval<U>())>
operator +(const Vector<T> &lhs, const Vector<U> &rhs)
{
Vector<decltype(lhs[0]+rhs[0])> res(lhs);
res += rhs;
return res;
}
declval as the default type arg
template <typename T, typename U,
typename R = decltype(std::declval<T>()+std::declval<U>())>
Vector<R> operator +(const Vector<T> &lhs, const Vector<U> &rhs)
{
Vector<R> res(lhs);
res += rhs;
return res;
}
What, in your opinion, is the best approach to implementing such a function? If there is a FOURTH best solution, I will be grateful.
, " " ?
,
Davide