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

Ber*_*ard 15 c++ std c++11

在此示例中,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;
}
Run Code Online (Sandbox Code Playgroud)

什么可以用来表现coord_squared_t在以下方面coord_t?标准库中是否有任何东西可以让我做一些像double_width<coord_t>::type获得正确宽度的东西,而不是明确选择类型?

C++ 11或C++ 14很好.

Tar*_*ama 25

你可以使用boost::int_t:

using coord_squared_t = boost::int_t<sizeof(coord_t)*CHAR_BIT*2>::least;
Run Code Online (Sandbox Code Playgroud)

  • 你可以考虑使用8-> CHAR_BIT (6认同)
  • @Bernard提升有什么问题?它甚至只是标题的一部分. (5认同)
  • @Bernard Boost是我们都需要的标准库缺失部分的高质量提供商.我想你会喜欢Boost :) (3认同)

Bar*_*rry 11

如果您不想使用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
Run Code Online (Sandbox Code Playgroud)

然后:

using coord_squared_t = next_size_t<coord_t>;
Run Code Online (Sandbox Code Playgroud)

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

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> { };
Run Code Online (Sandbox Code Playgroud)

这样,类似的东西by_size<45>::typeint_least64_t由于继承.然后这就像Boost的回答一样:

using coord_squared_t = by_size_t<2 * CHAR_BIT * sizeof(coord_t)>;
Run Code Online (Sandbox Code Playgroud)