0

I have the following problem/question: Suppose that i have a template class Couple which have two attributes x and y of type xobject. I can easily define the sum between Couple of the same class simply defining the sum element by element, if it is defined the sum of the template object, i.e.:

Couple operator+(Couple in)
{
 return Couple((*this).x+in.x,(*this).y+in.y);
}

With this implementation i can compute the sum between Couple<int> element. I don't exactly understand how i can define the sum between Couple<int> and Couple<something> inside that class. The problem is that i cannot specialize the sum inside the class between classes that are not yet implemented, i.e., i cannot write

Couple<'int'> Couple<'int'>::operator+(Couple<'something'>)

inside the Couple class.
Do you have any idea how to do this?
My first idea was to use a second template parameter inside the operator but the results was not so good since doing this i allow only the one verse sum and not in both verse.
I hope that i explained the problem in a decent way.

Nicola
  • 1
  • 1
  • Do you really need specializations? Normally you would use something like `template struct foo { template foo operator+(foo rhs) { stuff } };` – NathanOliver Feb 03 '17 at 15:30
  • If you want to apply type conversions on all parameters ( including the one pointed to by `this` ) to a function the function has to be at least a non-member function (may even a friend function ). – clickMe Feb 03 '17 at 15:33
  • The double template should not work since the sum of Couple and Couple is different from the sum Couple and Couple (it differs for the output, and i don't want to use C++14). – Nicola Feb 03 '17 at 15:37

1 Answers1

2

You can use a friend template function:

template <typename T>
class Couple
{
private:
    T x, y;

public:
    Couple(T xx, T xy) : x{xx}, y{xy} { }

    template <typename T0, typename T1>
    friend Couple<std::common_type_t<T0, T1>> 
    operator+(const Couple<T0>& x0, const Couple<T1>& x1);
};

template <typename T0, typename T1>
Couple<std::common_type_t<T0, T1>> 
operator+(const Couple<T0>& x0, const Couple<T1>& x1)
{
    return {x0.x + x1.x, x0.y + x1.y};
}

I am using std::common_type_t to compute a type that suitable for the T0 + T1 addition.

coliru example


You may not need friend if you expose getters for x and y, as SebTu mentioned in the comments.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416