Search code examples
c++c++14operator-overloading

C++ auto return type deduction in operator+=


I'm have written below C++ code for overloading the operator+=, that takes in p1 that is a reference, and then later returns p1.

template<typename T, typename T2> 
inline auto operator+=(std::pair<T, T2>& p1, std::pair<T, T2> const& p2)
{
  auto& [x1, y1] = p1;
  auto& [x2, y2] = p2; 

  x1 += x2;
  y1 += y2;

  return p1;
}

I want the operator+= to return a reference, aka type of "std::pair<T, T2>&" --

My question is, is it needed to return decltype(auto), or does the compiler deduce that auto must be a reference in this case, as the reference p1 is being returned. -- "auto" from my understanding does not generally deduce reference.

I'm unclear if it even would make sense for operator+= to return an rvalue instead of a reference.


Solution

  • You should declare the function as returning auto&, rather than auto:

    inline auto& operator+=(std::pair<T, T2>& p1, std::pair<T, T2> const& p2)
    //         ↑
    

    You could alternatively use decltype(auto), but I find that less clear that it gives a reference type.