gpt4 book ai didi

c++ - 如何统计模板类的CRTP子类个数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:21 24 4
gpt4 key购买 nike

有谁知道用CRTP统计一个对象的子类个数的方法吗?

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

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

const unsigned int ObjectSubClassCount = ...;

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

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

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

有谁知道这样做的方法吗?

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

最佳答案

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

// 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 方面没有足够的经验,但我怀疑这是否可行。

关于c++ - 如何统计模板类的CRTP子类个数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11113702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com