पर विचार करें निम्नलिखित सहायक structs:मानक के अनुसार, एक पूर्णांक में मूल्य प्रतिनिधित्व बिट्स की संख्या?
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>()
> {};
हर अभिन्न प्रकार के लिए std::is_integral<T>::value
है T
ऐसी है कि true
छोड़कर bool
मानक से, मैं गारंटी है, कि:
bit_count_1
,bit_count_2
औरbit_count_3
एक ही मानN
T x = 1; x <<= (N - 1)
अच्छी तरह से परिभाषित 01 है
T x = ~static_cast<T>(0); x >>= (N - 1)
अच्छी तरह से
मैं वर्तमान में एक सी ++ प्रस्ताव पर काम कर रहा हूँ परिभाषित किया गया है, तो मैं यकीन नहीं है कि इस मानक के अनुसार सही है, या नहीं, और पल के लिए यह मेरे लिए एक छोटे से स्पष्ट नहीं है की जरूरत है।
उचित दर्शकों को आकर्षित करने में सहायता के लिए आप [टैग: भाषा-वकील] के लिए इस प्रश्न पर टैग में से एक को स्वैप करना चाहेंगे। – Angew
... और सादे "सी ++" टैग के लिए एक और, जिसे सी ++ 11 और सी ++ 14 से अधिक का पालन किया जाता है। मैं या तो [टैग: सी ++ 11] या [टैग: मानकों] छोड़ दूंगा, लेकिन मैं इसे आपके पास छोड़ दूंगा। –