I'm currently developing a custom C++ container library that is similar to std::vector
, but I also want to have features of std::span
baked in. In particular, I want to be able to write functions that take in a std::span
-like parameter, and also work with a std::vector
-like argument.
What I can do is to construct a class, say my_vector
, and another class my_span
that can be converted from the class my_vector
. This is what the STL does, and I know it's usually a good idea to imitate the standard library. But I had this idea that my_span
is basically a my_vector
that does not own memory, and so it is possible to implement the two classes using inheritance. Here is what it looks like in code.
class my_vector;
class my_span {
private:
/* span sees [data_ + start_, data_ + stop_) */
T* data_;
size_t start_;
size_t stop_;
friend class my_vector;
public:
/* Member functions operating on non-owning memory */
};
class my_vector : public my_span {
private:
size_t cap_;
public:
/* Member functions like resize, push_back, etc. */
};
Now my colleague is rejecting this idea based on the following reasons. To be fair, my representation of his objections might not be faithful.
- It is counter-intuitive that a span is defined before the actual container.
- Inheritance is used when the derived class is extended, but the class
my_vector
has the condition that its memberstart_
will always be0
. (There are reasons that force the pointerdata_
to always point at the start of the allocated memory. This is why I can't just use a pointer and the length of the span.)
On the other hand, I believe this design has the following benefits.
- If you think about it,
my_vector
still "is a"my_span
. It's just amy_span
that owns memory and can change size. - Every member function that operates on non-owning memory can be declared and implemented only once; the class
my_vector
automatically inherits it. - To use
my_vector
as amy_span
, you don't need to create a newmy_span
instance. Up-casting is much more natural than a constructor.
I haven't seen a design that follows this pattern, so I wanted to get more opinions on whether this is a good design.