Is there a name for this kind of template in C ++?

I thought about this pattern which allows you to use a base class as a namespace for its derivatives, which can be neat if all your derivatives are known in advance. One case where this might look pretty is when you want to use adjectives for your subclasses. Does this template have a name?

class Flag
{
public:
  class White;
  class Chequered;
  // ...
};

class Flag::White: public Flag
{
  // ...
};

class Flag::Chequered: public Flag
{
  // ...
};

      

+3


source to share


2 answers


Using a class as a namespace is anti-pattern. Use instead namespace

.

Nested classes cannot be declared using

, so without typedef

you you will have no choice but to refer to Flag::Chequered

rather than the Chequered

client code. As you mentioned, all derivatives must be known in advance. They cannot be declared without definition class Flag

. Simply having a closure namespace

has advantages such as using from operators std::relops

for a cluster of classes.

Aesthetics are never expiated. Here's an alternative:



namespace flags {
class Base;
class White;
class Chequered;
}

typedef flags::Base Flag; // independent concept goes into enclosing namespace

      

I don't know the name of the practice of using adjectives for class names, but it looks pretty. Short names are good and the operator ::

always helps with that.

+4


source


They are called extremely complex namespaces without actually using the keyword namespace

.



The concept itself is called Inner Class , although not uncommon in some languages ​​such as Java.

+2


source







All Articles