c++ - 如何为全局类型设置静态计数器?
问题描述
我想要一个静态计数器,每次创建另一种类型时都会递增,类。这是我尝试过的:
template <typename Type>
class Sequential_ID_Dispenser
{public:
static inline int nextDispensed = 0;
static int getID() { return nextDispensed++; }
};
struct DummyTypeForComponentIDs {}; // So that the same type is passed to getID()
template <typename T>
struct Component {
static inline int componentTypeID = Sequential_ID_Dispenser<DummyTypeForComponentIDs>::getID();
};
// The reason I've made it inherit like this is so that any time I add a new Component type/struct it'll automatically get an ID for that type
struct Hat : Component<Hat> {};
struct Tie : Component<Tie> {};
int main()
{
int id = Hat::componentTypeID; // = 0
id = Tie::componentTypeID; // = 1
}
这行得通。但我想选择轻松地从任何其他组件继承,但它不能像这样工作,例如:
template <typename T>
struct Component {
static inline int componentTypeID = Sequential_ID_Dispenser<DummyTypeForComponentIDs>::getID();
};
struct Hat : Component<Hat> {};
struct Tie : Component<Tie> {};
struct BlueHat : Hat {};
int main()
{
int id = Hat::componentTypeID; // = 0
id = Tie::componentTypeID; // = 1
id = BlueHat::componentTypeID; // = 0, gets the same number as struct Hat : Component<Hat>{}
}
有没有好的解决方案?理想情况下,我想定义任何新结构而不将参数传递给基本构造函数。我意识到我为此使用了 CRTP,这正是我为使其工作所做的工作,但必须有更简单的方法,对吧?
编辑:实际上我很惊讶解决方案并不容易,我只想为我在全局命名空间中创建的每个类获取一个新 ID,我猜是编译时或运行时。
解决方案
您不需要继承类型上的(运行时)计数器。
您甚至可以使用模板变量 (C++14):
std::size_t getId()
{
static std::size_t counter = 0;
return counter++;
}
template <typename T>
std::size_t Id = getId();
演示。
推荐阅读
- c# - 如何在有 HttpGetAttribute 的地方添加 HttpHeadAttribute?
- html - 结合 rowspan 和 colspan 的引导程序
- docker - 我怎样才能让我的容器从开始 -> 健康
- java - 如何将 .aar 包的所有内容转换为 .jar 包?
- excel - 从excel工作簿自动创建csv文件
- github - 如何从 master 以外的分支运行 GitHub Action?
- performance - 英特尔 LLC 的一些奇怪行为
- python - 在不使用的情况下构建 django detailview 和 listview
- snowflake-cloud-data-platform - 计算雪花中数据库的数据存储
- javascript - 如何仅在调用 stream.requestFrame() 时记录 HTML 画布并保存结果?