Given the following:
template
class A
{
public:
static const unsigned int ID = ?;
};
I want ID to generate a unique c
It is possible to generate a compile time HASH from a string using the code from this answer.
If you can modify the template to include one extra integer and use a macro to declare the variable:
template struct A
{
static const int id = ID;
};
#define DECLARE_A(x) A
Using this macro for the type declaration, the id member contains a hash of the type name. For example:
int main()
{
DECLARE_A(int) a;
DECLARE_A(double) b;
DECLARE_A(float) c;
switch(a.id)
{
case DECLARE_A(int)::id:
cout << "int" << endl;
break;
case DECLARE_A(double)::id:
cout << "double" << endl;
break;
case DECLARE_A(float)::id:
cout << "float" << endl;
break;
};
return 0;
}
As the type name is converted to a string, any modification to the type name text results on a different id. For example:
static_assert(DECLARE_A(size_t)::id != DECLARE_A(std::size_t)::id, "");
Another drawback is due to the possibility for a hash collision to occur.