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

后端 未结 2 1672
甜味超标
甜味超标 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:03

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

    template  struct next_size;
    template  using next_size_t = typename next_size::type;
    template  struct tag { using type = T; };
    
    template <> struct next_size  : tag { };
    template <> struct next_size : tag { };
    template <> struct next_size : tag { };
    template <> struct next_size : tag { };
    
    // + others if you want the other int types
    

    And then:

    using coord_squared_t = next_size_t;
    

    Alternatively you can specialize based on number of bits:

    template  struct by_size : by_size { };
    template  using by_size_t = typename by_size::type;
    template  struct tag { using type = T; };
    
    template <> struct by_size<8>  : tag { };
    template <> struct by_size<16> : tag { };
    template <> struct by_size<32> : tag { };
    template <> struct by_size<64> : tag { };
    

    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)>;
    

提交回复
热议问题