C++标准不需要整数类型的精确大小,这有时会导致非常意外的结果.然后,一些聪明的人引入了<cstdint>包含(可选)typedef 的头文件,例如int64_t具有正好64位宽度的类型.这不是想要的.
是否存在(可能是可选的)整数类型,其属性sizeof(mysterious_type) == 2适用于定义的任何系统?
推理:我正试图弄清楚系统的结束.为此,在审查了这个板上的许多问题之后,我虽然只想定义一个大小为2的整数类型,给它分配一个并检查endianess,如下所示:
enum endianess { LITTLE_ENDIAN, BIG_ENDIAN };
typedef utwowitdhtype test_t; // some unsigned type with width 2
endianess inspectSystem() {
static_assert(sizeof(twowitdhtype) == 2, "twowitdhtype is not size 2??!?!!");
test_t integral = 0x1;
return *reinterpret_cast<char*>(&integral) == 0 ? BIG_ENDIAN : LITTLE_ENDIAN;
}
Run Code Online (Sandbox Code Playgroud)
虽然这是为什么我会对这种类型感兴趣的原因,但找到这样的类型不是为了解决问题而是出于好奇.
如果您使用的是char大小为!= 8位的机器,那么您将需要解决更大的可移植性问题 - 这样做static_assert(CHAR_BIT == 8, "assuming 8-bit chars")比以虚假可移植性为名做奇怪的事情 - 如果你不能测试一下,你怎么能说你做对了?
虽然找到endianess它根本没用,但你可以通过使用类型特征来获得这种类型.
#include <type_traits>
template<typename T>
struct Identity
{
typedef T type;
};
template<typename... Args>
struct ShortTypeFinder;
template<>
struct ShortTypeFinder<>
{
};
template<typename Head, typename... Tail>
struct ShortTypeFinder<Head, Tail...>
{
typedef typename std::conditional<sizeof(Head) == 2, Identity<Head>, ShortTypeFinder<Tail...>>::type::type type;
};
typedef ShortTypeFinder<short, int, long, long long>::type integral_type_with_sizeof_two;
int main()
{
integral_type_with_sizeof_two x = 0;
static_assert(sizeof x == 2, "sizeof(x) must be 2");
static_assert(std::is_same<integral_type_with_sizeof_two, short>::value, "it's short on my machine");
}
Run Code Online (Sandbox Code Playgroud)
如果这种类型不存在,ShortTypeFinder<TYPES>::type则无法编译.
| 归档时间: |
|
| 查看次数: |
195 次 |
| 最近记录: |