mardi 4 octobre 2016

C++ classes with the same data structure

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. Normally this would not make sense, but here

  • Derived can be constructed from Base (the constructor was imported with a using declaration in the example),
  • Derived and 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?

Aucun commentaire:

Enregistrer un commentaire