使用常量设置变量类型

Use constant to set variable type

本文关键字:变量 类型 设置 常量      更新时间:2023-10-16

我想知道,如果这是:

#define size 8
#if ( 0 < size ) and ( size <= 16 )
  static unsigned char value;
#elif ( 8 < size ) and  ( size <= 16 )
  static unsigned short value;
#elif ( 16 < size ) and  ( size <= 32 )
  static unsigned value;
#elif ( 32 < size ) and  ( size <= 64 )
  static unsigned long value;
#else
  return 0;
#endif
#undef size

常数是否可能?我试过:

const unsigned char size = 8;
if ( ( 0 < size ) &&  ( size <= 8 ) ) {
  static unsigned char value;
} else if ( ( 8 < size ) &&  ( size <= 16 ) ) {
  static unsigned short value;
} else if ( ( 16 < size ) &&  ( size <= 32 ) ) {
  static unsigned value;
} else if ( ( 32 < size ) &&  ( size <= 64 ) ) {
  static unsigned long value;
} else {
  return 0;
}

但结果是:

致命错误:使用未声明的标识符"value"

这可能吗?

在运行时不能对变量使用不同的类型。类型在编译时确定。

因此,第一个选项有效,但第二个选项无效。

当然,可能有一些模板解决方案是有效的,比如下面sehe的建议。

要创建位图,可以使用std::bitset<size>,其中size是位数。这将适用于从0开始的任何数量的位。。与内存或地址空间中的内容一样多,以先用完的为准。

您可以使用

typedef boost::uint_t<16>::exact my_uint16_t;
typedef boost::uint_t<8>::exact  my_uint8_t;
// etc.

这将适用于compiletime常量:

constexpr int mybitcount = 8;
void foo(boost::uint_t<mybitcount> ui8)
{
}

参见Boost Integer

template<int Bits>
struct uint_t 
{
    /* Member exact may or may not be defined depending upon Bits */
    typedef implementation-defined-type  exact;
    typedef implementation-defined-type  least;
    typedef uint_fast_t<least>::fast      fast;
};

您可以将std::conditional用作:

template<int N>
using uint = typename std::conditional< N<=8, unsigned char,
                           std::conditional< N<=16, unsigned short,
                                std::conditional< N<=32, unsigned int
                                     std::conditional< N<=64, unsigned long,
                                          void>>>>:type;

然后将其用作:

uint<8>   _08BitsUInt; //as long as N <= 8
uint<16>  _16BitsUInt; //as long as N <=16 and N > 8
uint<32>  _32BitsUInt; //as long as N <=32 and N > 16
uint<64>  _64BitsUInt; //as long as N <=64 and N > 32

希望能有所帮助。