如何计算模板类的CRTP子类数?

Ser*_*rge 5 c++ counter subclass crtp template-meta-programming

有没有人知道使用CRTP计算对象子类数的方法?

假设我们有类似于以下设置:

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

const unsigned int ObjectSubClassCount = ...; 

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

class Second : public Object<Second>
{
    ....
};
Run Code Online (Sandbox Code Playgroud)

等等,使用TMP,我们可能有一个ObjectSubClassCount代表子类总数的常量()?

有谁知道这样做的方法?

编辑:我想稍后将结果用作模板参数,所以我需要用TMP来完成...

dus*_*aer 2

如果不需要稍后使用结果作为模板参数,我会尝试这样做:

// 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);
Run Code Online (Sandbox Code Playgroud)

没试过但应该可以。为了再次将结果用作模板参数 (MPL),我在 MPL 方面没有足够的经验,但我怀疑这是可能的。