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

隐身守侯 提交于 2021-01-17 23:32:19

问题


In this example, coord_squared_t is the alias for an integer type with at least twice the size of the integer type 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;
}

What could be used to express coord_squared_t in terms of coord_t? Is there anything in the standard library that allows me to do something like double_width<coord_t>::type to get the correct width, instead of explicitly choosing the type?

C++11 or C++14 are fine.


回答1:


You could use boost::int_t:

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



回答2:


If you don't want to use Boost, you could just implement this manually with some specializations:

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

And then:

using coord_squared_t = next_size_t<coord_t>;

Alternatively you can specialize based on number of bits:

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

This way, something like by_size<45>::type is int_least64_t due to inheritance. And then this becomes just like the Boost answer:

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


来源:https://stackoverflow.com/questions/38852678/c-integer-type-twice-the-width-of-a-given-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!