最简单的方法只是一个函数
int nextId() {
static int rval = 1;
return rval++;
}
class A { public: static const id = nextId(); };
class B { public: static const id = nextId(); };
class C { public: static const id = nextId(); };
只要您不需要在程序开始时在动态初始化中使用 ID,这将起作用。
编辑:如果这还不够,下一步是对模板中的静态变量做同样的事情。这适用于编译单元,但仍然是动态初始化时间。
template <typename DummyT = void>
struct CommonCounter
{
public:
static int nextId() {
static int rval = 1;
return rval ++;
}
};
template <typename T>
struct IdFor
{
static int value()
{
static int rval = CommonCounter<>::nextId();
return rval;
}
};
class A { public: static const id = IdFor<A>::get(); };