I am creating a vector math library templated on the type and number of elements. There is a SizedVectorBase
struct where the number of elements is a member variable to prevent code bloat from vector functions that differ only in the size of the loop (see Scott Meyers' Effective C++ Item 44). I want component-wise operator overloads that loop through each element like +=
and *=
to be in the base class for the code bloat. However, since all Vectors derive from SizedVectorBase
, I want to prevent those operations between vectors of different sizes.
template<typename T>
struct SizedVectorBase
{
private:
std::size_t size;
T* pData;
protected:
SizedVectorBase<T>& operator+=(const SizedVectorBase<T>& rhs)
{
for(std::size_t i = 0; i < size; ++i)
{
pData[i] += rhs.pData[i];
}
return *this;
}
};
template<typename T, std::size_t n>
struct Vector : public SizedVectorBase<T>
{
std::array<T, n> data;
Vector<T, n>& operator+=(const Vector<T, n>& rhs)
{
static_cast<SizedVectorBase<T>&>(*this) += static_cast<const SizedVectorBase<T>&>(rhs);
return *this;
}
};
I tried std::enable_if
in SizedVectorBase
, but it doesn't appear that you can access the size member of specific instances *this
and rhs
. I got compile errors like "error C2355: 'this': can only be referenced inside non-static member functions or non-static data member initializers" and "error C2065: 'rhs': undeclared identifier"
typename std::enable_if<this->size == rhs.size>::type
SizedVectorBase<T>& operator+=(const SizedVectorBase<T>& rhs)
I then tried to make the functions protected and call them in the derived class, but I get a compile warning that I cannot access the protected member:
error C2248: 'SizedVectorBase::operator +=': cannot access protected member declared in class 'SizedVectorBase' with [ T=int ]
How can I prevent +=
from working with different sized vectors while retaining the sized loop in SizedVectorBase
?
std::array
assignable? Even if not, why not simply usestd::copy
? BTW2:T
isALL_UPPERCASE
, which suggests it is a macro. – Ulrich Eckhardt+=
byVector
anyway and that method indeed depend of bothT
andn
. – Jarod42