I have created a Vector class that takes the number of elements and the element type as template arguments.
template<int n, class T>
class Vector
{
public:
T data[n];
Vector()
: data{}
{
}
Vector(T const value)
{
std::fill_n(data, n, value);
}
template<class ...U, typename std::enable_if<sizeof...(U) == n, int>::type = 0>
Vector(U &&...u)
: data{std::forward<U>(u)...}
{
}
T& operator[](int const index)
{
return data[index];
}
template<class U>
operator Vector<n, U>()
{
Vector<n, U> out;
std::copy_n(data, n, out.data);
return out;
}
};
I want to have operators for the class, but in order for them to do conversions between vectors with different element types they need to be friend functions declared and defined inside the class body. But I also want to have 3 specialized template classes for Vector 2, 3, and 4. Since I do not want to have to write all the operators 4 times, once inside each class body. Could I just use this operator with an additional template argument for the element type of the right hand side vector?
template<int n, class T, class U>
inline Vector<n, T>& operator+=(Vector<n, T> &lhs, Vector<n, U> const &rhs)
{
for(int i = 0; i < n; ++i)
{
lhs.data[i] += rhs.data[i];
}
return lhs;
}
There is probably a reason that people use friend operators inside the class instead of doing it this way, but it seems fine so far, have I overlooked something?