Home > front end >  Convert size in bytes to unsigned integral type
Convert size in bytes to unsigned integral type

Time:05-09

I am developing a library that needs to auto deduce the type of size (in bytes).

How to convert size (in bytes) to unsigned integral type?

The type deduced must be big enough to store data in the size, but that does not mean to use uint64_t in every case.

C 20 or below can be used.

To be clearer, I want to deduce a type to store data of the size but without memory waste.

For example:

magic<1> -> uint8_t
magic<2> -> uint16_t
magic<3> -> uint32_t
magic<7> -> uint64_t

CodePudding user response:

Immediately invoked lambda might help. You can also use std::conditional_t.

template<std::size_t N>
using magic = decltype([] {
  if constexpr (N <= 1)
    return std::uint8_t{};
  else if constexpr (N <= 2)
    return std::uint16_t{};
  else if constexpr (N <= 4)
    return std::uint32_t{};
  else {  
    static_assert(N <= 8);
    return std::uint64_t{};
  }
}());
  • Related