I have a base class that contains some data structure, and some derived class containing exactly the same data but endowed with some extra functions, say (for the sake of concreteness):
struct Derived : public std::vector<double>
{
// Constructors, define or inherit
using std::vector<double>::vector;
double norm() const;
}
Now in another part of the code, I would like to call the function norm()
on an object obj
of the base type std::vector<double>
. Normally this would not make sense, but here:
Derived
can be constructed from its base (the constructor was imported with a using declaration in the example),Derived
and itss base have precisely the same data members.
I could call:
Derived(obj).norm()
But I’d like to avoid unnecessary copies.
Is there a way to simply and safely reinterpret object with the same underlying data structure? Or maybe a design pattern to dress data structures with (rather large) sets of functions that avoids the problem completely?