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

后端 未结 2 1671
甜味超标
甜味超标 2021-01-01 19:30

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         


        
相关标签:
2条回答
  • 2021-01-01 20:01

    You could use boost::int_t:

    using coord_squared_t = boost::int_t<sizeof(coord_t)*CHAR_BIT*2>::least;
    
    0 讨论(0)
  • 2021-01-01 20:03

    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)>;
    
    0 讨论(0)
提交回复
热议问题