Public member without inheritance

I have a base class that looks something like this:

class Base
{
public:
  typedef std::shared_ptr<Base> ptr_t;
  typedef std::weak_ptr<Base> wptr_t;

  enum class Type { foo, bar, baz };

  Type x;
  // ...
};

I would like these inner types to be publicly available so that I can do things like Base::ptr_t my_ptr(new Base);and so on. But if I create a new class like this ...

class Derived : public Base
{
  // ...
};

Unfortunately, Derived::ptr_tit is still the base pointer. I would like Derived to publicly inherit xfrom Base, but not inherit ptr_t, wptr_tor Type. for instance

Derived a;
a.x = Base::Type::foo; // this should work
a.x = Derived::Type::foo; // but I want this to fail

Is it possible, perhaps some kind of magical use, friendor virtualsomething like that?

+3
source share
3 answers

Based on the answers of iammilind and Luc Danton, here is what I came up with:

class Base
{
private:
  // only 'BaseClass' is allowed to derive from Base
  Base() { }
  friend class BaseClass;
public:
  typedef std::shared_ptr<Base> ptr_t;
  typedef std::weak_ptr<Base> wptr_t;

  enum class Type { foo, bar, baz };

  Type x;
  // ...
};

class BaseClass : public Base
{
private:
  // make all the raw_Base types private
  using Base::ptr_t;
  using Base::wptr_t;
  using Base::Type;
};

class Derived : public BaseClass
{
  // define as usual, and now all is well in the world.
};

// now, to test it
class Derived2 : public Base { }; // fails

Derived d;
d.x = Derived::Type::foo; // fails
d.x = Base::Type::foo; // works
// Which is exactly what I wanted.

, , . , - Base - BaseClass, BaseClass -.

, , BaseClass . , BaseClass .

0

:

class Derived {
  typedef int Type;
};

Derived::Type ( , typedef ed)

+4
class Derived : public Base
{
  // This is now private
  using Base::ptr_t;
  using Base::wptr_t;
  // ...
};
+3
source

All Articles