jeudi 5 octobre 2017

Providing aliases to Parent class data array in C++

Probably not the wisest choice, but modelling a Vertex<T, N> class to abstract Vertex2<T>, Vertex3<T> and Vertex4<T> implementations, providing basic access. It's structured like this:

template<typename T, unsigned N>
class _Vertex {
    const unsigned _size = N;
    T _data[N];

public:
    inline _Vertex() : _data() {};

    inline T const& operator[](int pos) const { return _data[pos]; } 
    inline T      & operator[](int pos)       { return _data[pos]; }
};

Say I want to implement Vertex2<T> as a Vertex<T, 2>, and provide aliases like x and y. The most proper way would be adding functions like:

 inline T const& x() const { return (*this)[0]; }
 inline T      & x()       { return (*this)[0]; }

This would be repeated for every property, or alias I'd like to add. It's not a bad design, but usage proves tricky as, provided v is of type Vector2<float>, v.x() = 1.0f is not as friendly as v.x = 1.0f.

Is there any way to provide clearer, friendlier alias?

My main thoughts were "abusing" memory layout, providing access to _data[i] accordingly, but I have no idea where to start.

This question is based on my "re-imagination" of a vertex.h header file provided for an assigment, so this makes it related to homework, but I can assure you the end is not. It's just my curiosity holding me off doing my homework!

Aucun commentaire:

Enregistrer un commentaire