如何计算模板类的CRTP子类的数量? [英] How to count the number of CRTP subclasses of a template class?
问题描述
有没有人知道使用CRTP来计算对象子类数量的方法?
Does anyone know of a method to use CRTP to count the number of subclasses of an object?
假设我们的设置类似于下面的一个: p>
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>
{
....
};
等等,使用TMP,我们可能有一个常数> ObjectSubClassCount )表示子类的总数?
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?
编辑:我想以后使用结果作为模板参数,所以我需要它完成与TMP ...
I am wanting to use the result as a template parameter later on, so I need it to be done with TMP...
推荐答案
不需要使用结果作为模板参数,我会尝试这样做:
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);
尚未尝试,但应该这样做。要使结果再次作为模板参数(MPL),我没有足够的MPL经验,但我怀疑这是可能的。
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.
这篇关于如何计算模板类的CRTP子类的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!