переменный шаблон «SFINAE» не работает

Я пытаюсь реализовать код размера для формата cbor с «SFINAE», из-за отсутствия лучшего слова. Но это не работает, так как size_code<3>например, оценивает 0x1b, В чем дело?

template <::std::size_t N,
typename = ::std::enable_if_t<N <= 0x17>
>
constexpr ::std::uint8_t const size_code = N;

template <::std::size_t N,
typename = ::std::enable_if_t<(N > 0x17) &&
(N <= ::std::numeric_limits<::std::uint8_t>::max())
>
>
constexpr ::std::uint8_t const size_code = 0x18;

template <::std::size_t N,
typename = ::std::enable_if_t<
(N > ::std::numeric_limits<::std::uint8_t>::max()) &&
(N <= ::std::numeric_limits<::std::uint16_t>::max())
>
>
constexpr ::std::uint8_t const size_code = 0x19;

template <::std::size_t N,
typename = ::std::enable_if_t<
(N > ::std::numeric_limits<::std::uint16_t>::max()) &&
(N <= ::std::numeric_limits<::std::uint32_t>::max())
>
>
constexpr ::std::uint8_t const size_code = 0x1a;

template <::std::size_t N,
typename = ::std::enable_if_t<
(N > ::std::numeric_limits<::std::uint32_t>::max()) &&
(N <= ::std::numeric_limits<::std::uint64_t>::max())
>
>
constexpr ::std::uint8_t const size_code = 0x1b;

0

Решение

Вы не можете переопределять шаблоны переменных таким образом, поэтому ваш код не должен работать.

Это было бы намного проще с constexpr функция, что-то вроде этого:

template <typename T> constexpr T t_max = std::numeric_limits<T>::max();

constexpr std::uint8_t size_code (std::size_t n) {
if (n <= 0x17) return n;
if (n <= t_max<std::uint8_t>) return 0x18;
if (n <= t_max<std::uint16_t>) return 0x19;
if (n <= t_max<std::uint32_t>) return 0x1a;
if (n <= t_max<std::uint64_t>) return 0x1b;
}
3

Другие решения

Мои 2 цента:

template <::std::size_t N, typename = void>
constexpr ::std::uint8_t const size_code{};

template <::std::size_t N>
constexpr ::std::uint8_t const size_code<N, ::std::enable_if_t<N <= 0x17> > = N;

template <::std::size_t N>
constexpr ::std::uint8_t const size_code<N,
::std::enable_if_t<(N > 0x17) &&
(N <= ::std::numeric_limits<::std::uint8_t>::max())
>
> = 0x18;

template <::std::size_t N>
constexpr ::std::uint8_t const size_code<N,
::std::enable_if_t<
(N > ::std::numeric_limits<::std::uint8_t>::max()) &&
(N <= ::std::numeric_limits<::std::uint16_t>::max())
>
> = 0x19;

template <::std::size_t N>
constexpr ::std::uint8_t const size_code<N,
::std::enable_if_t<
(N > ::std::numeric_limits<::std::uint16_t>::max()) &&
(N <= ::std::numeric_limits<::std::uint32_t>::max())
>
> = 0x1a;

template <::std::size_t N>
constexpr ::std::uint8_t const size_code<N,
::std::enable_if_t<
(N > ::std::numeric_limits<::std::uint32_t>::max()) &&
(N <= ::std::numeric_limits<::std::uint64_t>::max())
>
> = 0x1b;
1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector