编译时常数id

扫码查看
本文介绍了编译时常数id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下:

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

我想让ID为每个T生成一个唯一的编译时间ID。 $ c> __ COUNTER __ 和boost PP库,但迄今为止都不成功。


$ b

编辑:ID必须可以在switch语句中使用。


$ b 编辑2:所有基于静态方法或成员的地址的答案都不正确。虽然他们创建一个唯一的ID,但是它们在编译时不能解析,因此不能用作switch语句的情况。

解决方案

这是足够的假设一个符合标准的编译器(相对于一个定义规则):

  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] ):


Given the following:

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

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?

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

Edit2: 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;

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

这篇关于编译时常数id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 06:58
查看更多