2

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) { /* ... */ }
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Arthur R.
  • 323
  • 2
  • 7

1 Answers1

0

You can save one template parameter, by defining the operators inline:

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

If you completely want to avoid writing repetitive code, macros would be a way to avoid that (whether that is good practice, and whether it helps or disturbs understanding the code, is probably a question of taste and context)

chtz
  • 17,329
  • 4
  • 26
  • 56