保证大小为 2 的类型?

Type with a guaranteed size of 2?

C++ 标准不要求整数类型的精确大小,这有时会导致非常意外的结果。一些聪明人随后引入了 <cstdint> header 包含(可选)typedef,例如 int64_t 用于正好具有 64 位宽度的类型。这不是想要的。

是否有一个(可能是可选的)整数类型与 属性 sizeof(mysterious_type) == 2 用于定义的任何系统?

推理: 我正在尝试找出系统的字节顺序。为此,在审查了这个板上的许多问题之后,我虽然我会定义一个大小为 2 的整数类型,为其分配一个并检查字节顺序,如下所示:

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;
}

虽然这是我对这种类型感兴趣的原因,但找到这种类型并不是为了解决问题,而是出于好奇。

只要一个字节由 8 位组成,sizeof(int16_t) 将始终为 2。还有一些类型需要至少 16 位的大小和其他一些有趣的类型。

http://en.cppreference.com/w/cpp/types/integer

如果您使用的计算机具有 char 大小 != 8 位,您将遇到更大的可移植性问题您将不得不解决 - 这是只做 static_assert(CHAR_BIT == 8, "assuming 8-bit chars") 比以虚假可移植性的名义做奇怪的事情更简单 - 如果你不能测试它,你怎么能说你做对了?

虽然对于查找字节顺序没有任何帮助,但您可以通过使用类型特征来获得这种类型。

#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");
}

如果这种类型不存在,ShortTypeFinder<TYPES>::type 将无法编译。