Skip to content

Instantly share code, notes, and snippets.

@kugland
Created February 18, 2019 08:57
Show Gist options
  • Save kugland/55f873d49143633515e61ca0f748b505 to your computer and use it in GitHub Desktop.
Save kugland/55f873d49143633515e61ca0f748b505 to your computer and use it in GitHub Desktop.
#include <cstdint>
template<bool Fits8Bit, bool Fits16Bit, bool Fits32Bit>
struct intopt_helper {
using signed_type = std::int64_t;
using unsigned_type = std::uint64_t;
};
template<>
struct intopt_helper<false, false, true> {
using signed_type = std::int32_t;
using unsigned_type = std::uint32_t;
};
template<>
struct intopt_helper<false, true, true> {
using signed_type = std::int16_t;
using unsigned_type = std::uint16_t;
};
template<>
struct intopt_helper<true, true, true> {
using signed_type = std::int8_t;
using unsigned_type = std::uint8_t;
};
template<std::intmax_t MinValue, std::uintmax_t MaxValue>
struct intopt {
using type = typename intopt_helper<
(MinValue >= INT8_MIN && MaxValue <= INT8_MAX),
(MinValue >= INT16_MIN && MaxValue <= INT16_MAX),
(MinValue >= INT32_MIN && MaxValue <= INT32_MAX)
>::signed_type;
};
template<std::uintmax_t MaxValue>
struct uintopt {
using type = typename intopt_helper<
(MaxValue <= UINT8_MAX),
(MaxValue <= UINT16_MAX),
(MaxValue <= UINT32_MAX)
>::unsigned_type;
};
template<std::uintmax_t MaxValue>
struct intopt<0, MaxValue> {
using type = typename uintopt<MaxValue>::type;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment