Search code examples
c++templatesoperator-overloadingreturn-type

Infer the (templated) return type of operator+ and other operators


I'm implementing a two-dimensional vector that can take any arithmetic type for its coordinates. I want to implement an operator+ operator that infers its return type from context in the same way something like unsigned x = 2l + 3.1; knows the result of the + should be unsigned because it is assigned to an unsigned.

what I have this far, inspired by Templates inferring type T from return type:

#include <array>
#include <type_traits>

template<typename T,
         typename = std::enable_if_t<std::is_arithmetic_v<T>, T>>
class Vec2
{
    std::array<T, 2> _data;

public:
    // Constructors
    Vec2(T x, T y): _data{x, y} {}

    // Operators
    template<typename TB, // second operand's coordinates type
             typename TR> // result's coordinates type
    Vec2<TR> operator+(const Vec2<TB> v) const
    {
        return Vec2<TR>(_data[0] + v._data[0],
                        _data[1] + v._data[1]);
    }
};

int main(void)
{
    Vec2 vi{0, 2};
    Vec2 vf{1.4, 2.2};

    Vec2<int> res = vi + vf;
}

And I get an error saying it couldn't deduce the type used for the return value:

$ g++ -Wall -Wextra -std=c++17 poc.cc
poc.cc: In function ‘int main()’:
poc.cc:29:24: error: no match for ‘operator+’ (operand types are ‘Vec2<int, int>’ and ‘Vec2<double, double>’)
   29 |     Vec2<int> res = vi + vf;
      |                     ~~ ^ ~~
      |                     |    |
      |                     |    Vec2<double,double>
      |                     Vec2<int,int>
poc.cc:17:14: note: candidate: ‘template<class TB, class TR> Vec2<TR> Vec2<T, <template-parameter-1-2> >::operator+(Vec2<TB>) const [with TB = TB; TR = TR; T = int; <template-parameter-1-2> = int]’
   17 |     Vec2<TR> operator+(const Vec2<TB> v) const
      |              ^~~~~~~~
poc.cc:17:14: note:   template argument deduction/substitution failed:
poc.cc:29:26: note:   couldn’t deduce template parameter ‘TR’
   29 |     Vec2<int> res = vi + vf;
      |                          ^~
poc.cc:29:15: warning: unused variable ‘res’ [-Wunused-variable]
   29 |     Vec2<int> res = vi + vf;
      |               ^~~

Solution

  • In C++, the + operator overload has no means of determining what its result will be assigned to. C++ simply does not work this way.

    In many cases, it is possible to devise a workaround alternative in a slightly different way. Start by having the + operator figure out what it's optimal return type should be:

    template<typename TB> // result's coordinates type
    auto operator+(const Vec2<TB> v) const
    {
        typedef decltype( static_cast<T>(0) + static_cast<TB>(0) ) ret_t;
    
        return Vec2<ret_t>(_data[0] + v._data[0],
                        _data[1] + v._data[1]);
    }
    

    You are ensuring that both T and TB are arithmetic types, so this is the simplest way of figuring it out via decltype.

    So, adding a Vec2 of ints to a Vec2 of doubles should produce a Vec2<double>. But what if this gets assigned to a Vec2<int>? Well, you simply need a conversion operator...

    template<typename TB>
    operator Vec2<TB>() const
    {
        return Vec2<TB>(_data[0], _data[1]);
    }
    

    ... and hope for the best.