fork download
  1. #include <iostream>
  2.  
  3. template <typename T> struct next_t {};
  4. template <> struct next_t<unsigned long long> { typedef unsigned long type; };
  5. template <> struct next_t<unsigned long> { typedef unsigned int type; };
  6. template <> struct next_t<unsigned int> { typedef unsigned short type; };
  7. template <> struct next_t<unsigned short> { typedef unsigned char type; };
  8.  
  9. template <typename Max_t, Max_t upto_n, typename Best_t=Max_t, typename Try_t=unsigned long long, bool try_is_better = (sizeof(Try_t) <= sizeof(Best_t) && upto_n == Max_t(Try_t(upto_n)))>
  10. struct tight_int {
  11. typedef typename tight_int<Max_t, upto_n, Best_t, typename next_t<Try_t>::type>::type type;
  12. };
  13.  
  14. template <typename Max_t, Max_t upto_n, typename Best_t, typename Try_t>
  15. struct tight_int<Max_t, upto_n, Best_t, Try_t, true> {
  16. typedef typename tight_int<Max_t, upto_n, Try_t, typename next_t<Try_t>::type>::type type;
  17. };
  18.  
  19. template <typename Max_t, Max_t upto_n, typename Best_t>
  20. struct tight_int<Max_t, upto_n, Best_t, unsigned char, true> {
  21. typedef unsigned char type;
  22. };
  23.  
  24. template <typename Max_t, Max_t upto_n, typename Best_t>
  25. struct tight_int<Max_t, upto_n, Best_t, unsigned char, false> {
  26. typedef Best_t type;
  27. };
  28.  
  29. int main() {
  30. typedef tight_int<size_t, 255>::type tight_255_t;
  31. typedef tight_int<size_t, 256>::type tight_256_t;
  32. typedef tight_int<size_t, 65535>::type tight_65535_t;
  33. typedef tight_int<size_t, 65536>::type tight_65536_t;
  34. std::cout << "255 : " << sizeof(tight_255_t) << std::endl;
  35. std::cout << "256 : " << sizeof(tight_256_t) << std::endl;
  36. std::cout << "65535 : " << sizeof(tight_65535_t) << std::endl;
  37. std::cout << "65536 : " << sizeof(tight_65536_t) << std::endl;
  38. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
255   : 1
256   : 2
65535 : 2
65536 : 4