【发布时间】:2020-12-22 23:40:14
【问题描述】:
我想要一个静态计数器,每次创建另一种类型类时都会递增。这是我尝试过的:
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,我猜是编译时或运行时。
【问题讨论】:
-
没有线索,但这是一个必须源于一个非常非常简洁的用例的问题。
-
你想在编译时知道它吗?
-
struct BlueHat : Hat, Component<BlueHat> {};怎么样? -
@Jarod42 那不是从 Component 继承了两次吗?