C++整数类型是给定类型宽度的两倍

C++ integer type twice the width of a given type

在此示例中,coord_squared_t 是整数类型的别名,其大小至少是整数类型 coord_t:

的两倍
typedef int_least32_t coord_t;

coord_squared_t CalculateSquaredHypothenuse(coord_t x, coord_t y){
    coord_squared_t _x=x;
    coord_squared_t _y=y;
    return _x*_x+_y*_y;
}

coord_t可以用什么来表示coord_squared_t?标准库中有什么允许我做类似 double_width<coord_t>::type 的事情来获得正确的宽度,而不是明确选择类型吗?

C++11 或 C++14 都可以。

您可以使用 boost::int_t:

using coord_squared_t = boost::int_t<sizeof(coord_t)*CHAR_BIT*2>::least;

如果您不想使用 Boost,您可以通过一些专业化手动实现:

template <class > struct next_size;
template <class T> using next_size_t = typename next_size<T>::type;
template <class T> struct tag { using type = T; };

template <> struct next_size<int_least8_t>  : tag<int_least16_t> { };
template <> struct next_size<int_least16_t> : tag<int_least32_t> { };
template <> struct next_size<int_least32_t> : tag<int_least64_t> { };
template <> struct next_size<int_least64_t> : tag<???> { };

// + others if you want the other int types

然后:

using coord_squared_t = next_size_t<coord_t>;

或者,您可以根据位数进行专业化:

template <size_t N> struct by_size : by_size<N+1> { };
template <size_t N> using by_size_t = typename by_size<N>::type;
template <class T> struct tag { using type = T; };

template <> struct by_size<8>  : tag<int_least8_t> { };
template <> struct by_size<16> : tag<int_least16_t> { };
template <> struct by_size<32> : tag<int_least32_t> { };
template <> struct by_size<64> : tag<int_least64_t> { };

这样,像 by_size<45>::type 这样的东西是 int_least64_t 由于继承。然后这就像 Boost 答案一样:

using coord_squared_t = by_size_t<2 * CHAR_BIT * sizeof(coord_t)>;