Given the following:
template
class A
{
public:
static const unsigned int ID = ?;
};
I want ID to generate a unique c
If non-monotonous values and an intptr_t
are acceptable:
template
struct TypeID
{
private:
static char id_ref;
public:
static const intptr_t ID;
};
template
char TypeID::id_ref;
template
const intptr_t TypeID::ID = (intptr_t)&TypeID::id_ref;
If you must have ints, or must have monotonically incrementing values, I think using static constructors is the only way to go:
// put this in a namespace
extern int counter;
template
class Counter {
private:
Counter() {
ID_val = counter++;
}
static Counter init;
static int ID_val;
public:
static const int &ID;
};
template
Counter Counter::init;
template
int Counter::ID_val;
template
const int &Counter::ID = Counter::ID_val;
// in a non-header file somewhere
int counter;
Note that neither of these techniques is safe if you are sharing them between shared libraries and your application!