编译时常量 id

鉴于以下内容:

template<typename T>
class A
{
public:
    static const unsigned int ID = ?;
};

我希望 ID 为每个 T 生成一个唯一的编译时 ID.我考虑过 __COUNTER__ 和 boost PP 库,但到目前为止都没有成功.我怎样才能做到这一点?

I want ID to generate a unique compile time ID for every T. I've considered __COUNTER__ and the boost PP library but have been unsuccessful so far. How can I achieve this?

ID 必须可用于 switch 语句中的情况

ID has to be usable as the case in a switch statement

Edit2:所有基于静态方法或成员地址的答案都不正确.尽管它们确实创建了唯一 ID,但它们在编译时无法解析,因此不能用作 switch 语句的情况.

All the answers based on the address of a static method or member are incorrect. Although they do create a unique ID they are not resolved in compile time and therefore can not be used as the cases of a switch statement.

推荐答案

假设编译器符合标准就足够了(关于一个定义规则):

This is sufficient assuming a standards conforming compiler (with respect to the one definition rule):

template<typename T>
class A
{
public:
    static char ID_storage;
    static const void * const ID;
};

template<typename T> char A<T>::ID_storage;
template<typename T> const void * const A<T>::ID= &A<T>::ID_storage;

来自 C++ 标准 3.2.5 一个定义规则 [basic.def.odr](粗体强调我的):

From the C++ standard 3.2.5 One definition rule [basic.def.odr] (bold emphasis mine):

... 如果 D 是一个模板并且在多个翻译中定义单位,则应适用上述列表中的最后四项要求模板中使用的模板封闭范围的名称定义(14.6.3),以及在点的从属名称实例化 (14.6.2).如果D的定义满足所有这些要求,那么程序的行为就好像有一个D 的定义. 如果 D 的定义不满足这些要求,则行为未定义.

... If D is a template and is defined in more than one translation unit, then the last four requirements from the list above shall apply to names from the template’s enclosing scope used in the template definition (14.6.3), and also to dependent names at the point of instantiation (14.6.2). If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined.

相关文章