How to: Template class that contains container of it's base class derived objects

66 Views Asked by At

I want to establish a template class model that is structured in such a way that there is a base template, which in turn is to be stored in a derived template class as an object in a std::unordered_map. Each object has a unique key, which can be of different data types (POD, struct, ...). I don't know how to tell the derived container class to use the type of the key of the passed child class for the key of the unordered_map. Specifically if the objects have been derived from the base class and then are no longer template classes due to specialization.

What I did so far:

   **  // The base class**
   template <typename IDType> class XRObject {
   public:
    XRObject() : ID_() {
    }

    XRObject( const IDType& id) : 
    ID_(id){
    }

    XRObject(const XRObject& other) : ID_(other.ID_)
    {
    }

    virtual ~XRObject() = default;

    IDType getID() const {
      return ID_;
    }
    void setID(const IDType& id) {
      ID_= id;
    };

  private:
    IDType  ID_;
  };


  // The derived container class
  template <class IDType=long, class T=XRObject> class XRObjectContainer : public XRObject<IDType> {
  public:

    using ptr_type = typename std::shared_ptr<T>;
    using container_type = typename std::unordered_map<**IDType of class T**, ptr_type>;

    using iterator = typename container_type::iterator;
    using const_iterator = typename container_type::const_iterator;

    using sorted_containter_type = typename std::multimap<std::wstring, **IDType of class T**>;
    using sorted_iterator = typename sorted_containter_type::const_iterator;

    XRObjectContainer() : XRObject<IDType>() {
    }

    XRObjectContainer(IDType id) {
    }

    XRObjectContainer(const XRObjectContainer& rhs) : XRObject<IDType>(rhs) {
    }

  protected:
    container_type         children_;
    sorted_containter_type sortedbyname_;
  };

  // Concrete class specialisation
  class XRUnit : public XRObject {
  public:

    XRUnit::XRUnit() : XRObjectContainer<long, XRUnit>(), Factor_(0.0, true) {
    }

    XRUnit::XRUnit(long id, double Factor) : XRObjectContainer<long, XRUnit>(id),
      Factor_(Factor) {

    }

  private:
    XRValue<double>     Factor_;

  };

  // The final container class using XRUnit as data members of the internal unordered_map container
  class XRUnits : public XRObjectContainer<std::string, XRUnit> {
  public:

    XRUnits::XRUnits() : XRObjectContainer<std::string, XRUnit>() {
    }

    XRUnits::XRUnits(const std::string& ID) : XRObjectContainer<std::string, XRUnit>(ID) {
    }

  };

I don't know how I can get the IDType of class XRUnit automatically determined by the compiler and used in the template class XRUnits as the key type of it's std::unordered_map member? The IDType of the XRObjectType derived class defers from the IDType of the contained unordered_map elements IDType.

0

There are 0 best solutions below