且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

编译时常量 id

更新时间:2022-03-05 17:36:42

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

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.