jeudi 10 août 2017

How to get reference to parent class?

I have an interface called Connection that only has pure abstract methods.

I also have an abstract class called AbstractConnection that looks like this:

template <typename T>
struct AbstractConnection : public Connection {
  explicit AbstractConnection(Parameters &params) noexcept;
  virtual ~AbstractConnection() noexcept;

 protected:
  std::shared_ptr<Socket<AbstractConnection>> socket_;
};

AbstractConnection uses the CRTP pattern to implement inheritance. My .cpp file looks like this:

template <typename T>
AbstractConnection<T>::AbstractConnection(Parameters &params) noexcept : Connection(params) { /*lots of code*/ }

template <typename T>
AbstractConnection<T>::~AbstractConnection() noexcept {}

template struct AbstractConnection<databaseclient::internal::specific::Connection>;

And then I have implementations of Connection that use AbstractConnection to share common code (this Connection object is inside a different namespace):

struct Connection : public AbstractConnection<Connection> {
  explicit Connection(Parameters &params) noexcept;
  virtual ~Connection() noexcept;
};

And it's constructor:

Connection::Connection(Parameters &params) noexcept : AbstractConnection<Connection>(params) {
socket_ = std::make_shared<Socket<AbstractConnection>>(this, true, params_.host, std::to_string(params_.port),                                                                 
}

My problem is that despite this Connection object inheriting from AbstractConnection, the compiler won't let me pass it as a parameter to Socket whose constructor looks like this:

template <class T>
struct Socket : public std::enable_shared_from_this<Socket<T>> {
  explicit Socket(T &delegate, const bool big_endian, const std::string &socket) {}
}

How can I declare Socket in my abstract connection but pass it a reference to a child of the abstract connection?

Aucun commentaire:

Enregistrer un commentaire