Rozważmy następujące przypisać struktury pomocnicze:Liczba bitów reprezentacji wartości w liczbie całkowitej, zgodnie z normą?
template <class T>
struct bit_count_1:
std::integral_constant<
std::size_t,
std::numeric_limits<typename std::make_unsigned<T>::type>::digits
> {};
template <class T>
struct bit_count_2:
std::integral_constant<
std::size_t,
std::numeric_limits<T>::digits + std::is_signed<T>::value
> {};
template <class T>
constexpr std::size_t compute_bit_count() {
using type = typename std::make_unsigned<T>::type;
constexpr type zero = 0;
constexpr type one = 1;
constexpr type max = ~zero;
type current = max;
std::size_t i = 0;
while (current) {
current >>= one;
++i;
}
return i;
}
template <class T>
struct bit_count_3:
std::integral_constant<
std::size_t,
compute_bit_count<T>()
> {};
dla każdej integralnej typu T
takie, że std::is_integral<T>::value
jest true
wyjątkiem bool
mam gwarancję, przez normę, że:
bit_count_1
,bit_count_2
ibit_count_3
mają tę samą wartośćN
T x = 1; x <<= (N - 1)
jest dobrze zdefiniowanaT x = ~static_cast<T>(0); x >>= (N - 1)
jest dobrze zdefiniowany
Ja obecnie pracuje nad wnioskiem C++, więc muszę być pewien, czy to prawda, zgodnie z normą, czy nie, i na chwilę obecną jest to trochę niejasne dla mnie.
Możesz zamienić jeden z tagów tego pytania na [tag: language-lawyer], aby przyciągnąć odpowiednich odbiorców. – Angew
... i jeszcze jeden dla zwykłego tagu "C++", który jest śledzony znacznie częściej niż C++ 11 i C++ 14. Chciałbym upuścić [tag: C++ 11] lub [tag: standards], ale zostawię to tobie. –