vendredi 26 octobre 2018

C++ Cast to "uncle class"

I have a Wrapper<T> template class.

I have a base class A.

I have a derived class B : public A.

What I want is to store a Wrapper<B> in a vector<Wrapper<A>>.

I know this technically not right as Wrapper<B> is not a direct subclass of Wrapper<A>

See inheritance diagram

But somehow, STL allow that for shared_ptr:

#include <memory>
#include <vector>
#include <iostream>

struct A
{
  A() {}
  virtual ~A() {}
  virtual void print() { std::cout << "A" << std::endl; }
};

struct B : public A
{
  B() {}
  virtual ~B() {}
  virtual void print() { std::cout << "B" << std::endl; }
};

int main()
{
  std::vector<std::shared_ptr<A>> v;

  v.push_back(std::make_shared<A>());
  v.push_back(std::make_shared<B>());

  for (auto &e : v)
    e->print();

  return 0;
}

How can I achieve the same result for my Wrapper<T> class ?

Best, Pierre

Aucun commentaire:

Enregistrer un commentaire