How to count the number of subclasses of a CRTP 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:

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

const unsigned int ObjectSubClassCount = ...; 

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

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

etc., so using TMP, could we have a constant ( ObjectSubClassCount) that represents the total number of subclasses?

Does anyone know how to do this?

Edit: I want to use the result as a template parameter later, so I need this to be done using TMP ...

+5
source share
2 answers

Without the requirement to use the result as a template parameter, later I would try to do it as follows:

// 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);

, . (MPL), MPL, , .

+2

, . , , ( , ...).

. , ; . CRTP, , . , Object < > templated from:

A: B:

( <type_traits> , )

template <typename T>   //SFINAE check for the existance of subclasscount static member
struct has_subclasscount
{

    template <typename U>
    static typename std::enable_if<sizeof(U::subclasscount) != 0, int>::type test(int);

    template <typename U>
    static char test(...);

    static const bool result = (sizeof(test<T>(0)) == sizeof(int))?(true):(false);
};


template <bool res, typename T>
struct return_subclasscount //the value to return is 0 if false
{
    static const int result = 0;
};


template <typename T>       
struct return_subclasscount<true, T>    //returns subclasscount only if the first parameter is true
{
    static const int result = T::subclasscount;
};


template <typename T>               //combines return_subclasscount and has_subclasscount
struct get_subclasscount
{
    static const int result = return_subclasscount<has_subclasscount<T>::result, T>::result;
};


template <typename This, typename Prev>
class Object
{
public:

    static const int subclasscount = 1 + get_subclasscount<Prev>::result;   //the subclass count
};


class sub1 : public Object<sub1, int>
{

};


class sub2 : public Object<sub2, sub1>
{

};


class sub3 : public Object<sub3, sub2>
{

};

3 - , . . .cpp :

int main() {

std::cout << sub3::subclasscount;

char c;
std::cin >> c;
}

, :

3

, . :

  • , , .
  • , , , ( , "endoflist", )/li >

, , , - . " ", " "; , -, ?

( , , subclasscount node )

- ?

0

All Articles