Is there an elegant way to declare a set of functions with the same template parameters?

4328 views c++ templates auto
9

For instance, let's say I have a simple 2D vector templated structure:

template <typename T>
struct Vec { T x, y; };

And a generic way to do summation:

template <typename T, typename U>
constexpr auto operator+(const Vec<T>& u, const Vec<U>& v) {
    return Vec<decltype(u.x + v.x)>{u.x + v.x, u.y + v.y};
}

But I have to rewrite template <typename T, typename U> for all the other basic operations (-, *, / etc.). I wish I could do something like:

template <typename T, typename U>
{
    constexpr auto operator+(const Vec<T>& u, const Vec<U>& v) { /* ... */ };
    constexpr auto operator-(const Vec<T>& u, const Vec<U>& v) { /* ... */ };
    /* ... */
}

Also, as said in this thread, auto is not permitted when nested within a decl-specifier, which means that the below solution isn't valid (even if it compiles somehow):

constexpr auto operator+(const Vec<auto>& u, const Vec<auto>& v) { /* ... */ }

answered question

1 Answer

10

What about providing them as friend functions and definitions also inside the Vec.

template <typename T> struct Vec 
{
   T x, y;

   friend constexpr Vec operator+(const Vec& lhs, const Vec& rhs) noexcept
   {
      return { lhs.x + lhs.x, rhs.y + rhs.y };
   }
   friend constexpr Vec operator+(const Vec& lhs, const Vec& rhs) { /* ... */ };
   friend constexpr Vec operator-(const Vec& lhs, const Vec& rhs) { /* ... */ };
};

posted this

Have an answer?

JD

Please login first before posting an answer.