Inheritance from protected classes in C +++

Suppose I have the following declaration:

class Over1
{
   protected:
      class Under1
      {
      };
};

I know I can do the following:

class Over2 : public Over1
{
   protected:
        class Under2 : public Under1
        {
        };
};

But is there a way to declare Under2 without Over2?

Since you have to extend Over1 to use any derivative of Under1, this may seem silly, but in this situation there may be 30 different flavors of Under. I can:

  • Put them all inside Over1: Not attractive, because Over2 can use 1 or 2 of them
  • Put them in their own version of Over: Not, since then you will have to multiply inherit from almost the same class.
  • Find a way to create kids under1 without creating kids over1

So is this possible?

Thank.

+3
source share
4 answers

, Over1.

class Over1
{
protected:
  class Under1
  {
  };

  template <typename T>
  class UnderImplementor;
};

struct Under2Tag;
struct Under3Tag;
struct Under4Tag;

template <>
class Over1::UnderImplementor<Under2Tag> : public Over1::Under1
{
};

template <>
class Over1::UnderImplementor<Under3Tag> : public Over1::Under1
{
};

template <>
class Over1::UnderImplementor<Under4Tag> : public Over1::Under1
{
};

, .

+1

, , . , , . Google ++ .

+1

Under1, Over1 . Under1 , .

, , , , :

class Over1
{
   protected:
      class Under1
      {
      };

   public:
      class Under1Interface : public Under1 
      {
      };
};

class Under2 : public Over1::Under1Interface
{
};

- :

class Over1
{
   protected:
      class Under1
      {
      };
};

class Under2 : private Over1, public Over1::Under1
{
};

:

class Under2;

class Over1
{
   friend class Under2;

   protected:
      class Under1
      {
      };
};

class Under2 : public Over1::Under1
{
};

, Over1s Under2 - - .

0

Sounds a little funky to me. Why not try structuring your code differently. I think that this can be a good candidate for a decorator sample, where you can wrap your base class with various decorators to achieve the desired functionality, various flavors "under" can be decorators. Just a thought, it's hard to say without knowing more about the intentions of your code.

0
source

Source: https://habr.com/ru/post/1697727/


All Articles