Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

c++11

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.

like image 387
Bernard Avatar asked Aug 09 '16 13:08

Bernard


2 Answers

You could use boost::int_t:

using coord_squared_t = boost::int_t<sizeof(coord_t)*CHAR_BIT*2>::least;
like image 72
TartanLlama Avatar answered Oct 22 '22 02:10

TartanLlama


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)>;
like image 32
Barry Avatar answered Oct 22 '22 02:10

Barry