使用常量设置变量类型
Use constant to set variable type
我想知道,如果这是:
#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
希望能有所帮助。
相关文章:
- c++类声明时,相同的例程,不同的成员变量类型
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- 创建类似于布尔值的变量类型
- std::cin 从控制台获取两种不同的变量类型,'storing'以后使用第二种类型?
- 如何使用变量模板比较 C++ 17 中的变量类型?
- 是否有一个库可以检查C++中的变量类型?
- 与不同变量类型相比,用于变量的 Clang AST 匹配器
- 继承类中的 C++ 成员变量类型重写
- 如何在编译器时动态获取元组内的变量类型C++?
- 在C++中动态分配变量类型
- 用于浮点值的最佳变量类型
- 定义变量类型
- 错误 - 变量类型 "X" 是一个抽象类 - c++
- 在函数 (c++) 中分配变量类型和大小数组
- 具有容器变量类型的类模板
- 获取变量类型名称
- 沿枚举 c++ 返回变量类型
- 是否可以通过模板指定抽象类变量类型
- 什么是变量类型位(32)
- C++ 在知道变量类型之前使用自动定义的变量