fork download
  1. #include <iostream>
  2. #include <tuple>
  3.  
  4. template <size_t size>
  5. struct min_type {
  6.  
  7. constexpr static inline size_t log2(size_t n) {
  8. return ( (n<2) ? 0 : 1+log2(n/2));
  9. }
  10.  
  11. constexpr static inline size_t get_index(size_t last,size_t value) {
  12. return value == 8 ? last : get_index(last+1,value/2);
  13. }
  14.  
  15. constexpr static inline std::size_t min_type_size(std::size_t v) {
  16. v--; v |= v >> 1; v |= v >> 2; v |= v >> 4;
  17. v |= v >> 8; v |= v >> 16; v++;
  18. return v < 8 ? 8 : v;
  19. }
  20.  
  21. using type_options = std::tuple<uint8_t,uint16_t,uint32_t,uint64_t>;
  22.  
  23. using type = typename std::tuple_element<
  24. get_index(0,min_type_size(log2(size))),
  25. type_options>::type;
  26. };
  27.  
  28. template<typename T, size_t max_elements_to_store>
  29. class testClass {
  30. //private:
  31. public:
  32. T data[max_elements_to_store];
  33. typename min_type<max_elements_to_store>::type currently_selected_element;
  34. };
  35.  
  36. int main()
  37. {
  38. min_type<0xff>::type uint_8_value;
  39. min_type<0xffff>::type uint_16_value;
  40. min_type<0xffffffff>::type uint_32_value;
  41. min_type<0xffffffffffffffff>::type uint_64_value;
  42.  
  43. static_assert(std::is_same< decltype(uint_8_value),uint8_t>::value,"...");
  44. static_assert(std::is_same< decltype(uint_16_value),uint16_t>::value,"...");
  45. static_assert(std::is_same< decltype(uint_32_value),uint32_t>::value,"...");
  46. static_assert(std::is_same< decltype(uint_64_value),uint64_t>::value,"...");
  47.  
  48. testClass<int,12> testcls;
  49.  
  50. static_assert(std::is_same< decltype(testcls.currently_selected_element),uint8_t>::value,"...");
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0s 4440KB
stdin
Standard input is empty
stdout
Standard output is empty