Created
October 22, 2018 09:18
-
-
Save SaitoAtsushi/f7d4964b27e22eb5efccd4aa2ab10116 to your computer and use it in GitHub Desktop.
元記事の趣旨とは違うけど、コンパイル時にテーブル生成をするのをやってみた。 これの件 → https://qiita.com/Kogia_sima/items/f47ea613d5274ab65ead
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdint> | |
#include <array> | |
using bitcount_table_t = std::array<int, 256>; | |
template<int n> | |
struct make_bitcount_table_helper { | |
constexpr static auto bitcount(std::uint8_t x) noexcept -> uint8_t { | |
return x==1 or x==0 ? x : (x bitand 1) + bitcount(x>>1); | |
} | |
template<class ... T> | |
constexpr static auto invoke(T... args) -> bitcount_table_t { | |
return make_bitcount_table_helper<n+1>::invoke(args ..., bitcount(n)); | |
} | |
}; | |
template<> | |
struct make_bitcount_table_helper<256> { | |
template<class ... T> | |
constexpr static auto invoke(T... args) -> bitcount_table_t { | |
return bitcount_table_t{args ...}; | |
} | |
}; | |
static constexpr auto make_bitcount_table(void) -> bitcount_table_t { | |
return make_bitcount_table_helper<0>::invoke(); | |
} | |
auto bitcount(std::uint8_t n) noexcept -> int { | |
static constexpr auto bitcount_table = make_bitcount_table(); | |
return bitcount_table[n]; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifdef __cplusplus | |
#include <cstdint> | |
auto bitcount(std::uint8_t n) noexcept -> int; | |
#else | |
extern "C" int bitcount(unsigned char n); | |
#endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "bitcount.h" | |
int main(void) { | |
for(int i=0; i<256; i++) std::cout << bitcount(i) << ','; | |
std::cout << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment