C ++ 11 operator overload with return type subtraction

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;   // s1 MUST be of type Vector<float> == {2.5, 4.5}
auto s2 = iv + fv;   // s2 MUST be of type Vector<float> == {2.5, 4.5}

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

+4
1

, " ", . , , std::common_type, :

template<typename T, typename U>
struct VectorCommonType : std::common_type<T,U> {};

template<typename T, typename U>
using VectorCommonTypeT = Vector<typename VectorCommonType<T,U>::type>;

, ( ) , . :

template<typename T, typename U> 
VectorCommonTypeT<T,U> operator+(const Vector<T> &lhs, const Vector<U> &rhs)
{
    VectorCommonTypeT<T,U> res(lhs);
    res += rhs;
    return res;
}
+2

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


All Articles