Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of CRTP subclasses of a template class?

Does anyone know of a method to use CRTP to count the number of subclasses of an object?

Suppose we had a setup similar to the following one:

template <typename T>    
class Object
{
    ....  
};

const unsigned int ObjectSubClassCount = ...; 

class Subobject : public Object<SubObject>
{
    ....
};

class Second : public Object<Second>
{
    ....
};

and so on, such that, using TMP, we might have a constant (ObjectSubClassCount) that represents the total number of subclasses?

Does anyone know a way to do this?

Edit: I am wanting to use the result as a template parameter later on, so I need it to be done with TMP...

like image 947
Serge Avatar asked Jun 20 '12 06:06

Serge


Video Answer


1 Answers

Without the requirement to use the result as a template parameter later I would try it doing like this:

// Class which increments a given counter at instanciation
struct Increment {
  Increment(std::size_t& counter)
  {
    counter++;
  }
};

// This is your template base
template <typename T>    
class Object
{
  private:
    // For every instanciation of the template (which is done for a subclass)
    // the class counter should get incremented
    static Increment incrementCounter;
};

// This is the global object counter
static std::size_t classCounter;

// Static Member Variable
template<typename T>
Object<T>::incrementCounter(classCounter);

Haven't tried it but should do. To have the result available as a template parameter again (MPL) I don't have enough experience in MPL but I doubt this is possible.

like image 136
duselbaer Avatar answered Oct 09 '22 09:10

duselbaer