fork download
  1. #include <iostream>
  2. #include <typeinfo>
  3.  
  4. typedef signed char int8_t;
  5. typedef short int16_t;
  6. typedef int int32_t;
  7. typedef long long int64_t;
  8.  
  9. static int8_t const min8 = -128;
  10. static int8_t const max8 = 127;
  11.  
  12. static int16_t const min16 = -32768;
  13. static int16_t const max16 = 32767;
  14.  
  15. static int32_t const min32 = -2147483648LL;
  16. static int32_t const max32 = 2147483647;
  17.  
  18. /**
  19.  * Helper for IntTypeThatFits.
  20.  * Template parameters indicate whether the given number fits into 8, 16 or 32
  21.  * bits. If neither of them is true, it is assumed that it fits 64 bits.
  22.  */
  23. template <bool fits8, bool fits16, bool fits32>
  24. struct IntTypeThatFitsHelper { };
  25.  
  26. // specializations for picking the right type
  27. // these are all valid combinations of the flags
  28. template<> struct IntTypeThatFitsHelper<true, true, true> { typedef int8_t Result; };
  29. template<> struct IntTypeThatFitsHelper<false, true, true> { typedef int16_t Result; };
  30. template<> struct IntTypeThatFitsHelper<false, false, true> { typedef int32_t Result; };
  31. template<> struct IntTypeThatFitsHelper<false, false, false> { typedef int64_t Result; };
  32.  
  33. /// Finds the smallest integer type that can represent the given number.
  34. template <int64_t n>
  35. struct IntTypeThatFits
  36. {
  37. typedef typename IntTypeThatFitsHelper<
  38. (n <= max8) && (n >= min8),
  39. (n <= max16) && (n >= min16),
  40. (n <= max32) && (n >= min32)
  41. >::Result Result;
  42. };
  43.  
  44. template <typename X, typename Y>
  45. void print_impl(Y y) { std::cout << y << ": " << typeid(X).name() << "\n"; }
  46.  
  47. template <int64_t n>
  48. void print() {
  49. typedef typename IntTypeThatFits<n>::Result Result;
  50. print_impl<Result>(n);
  51. }
  52.  
  53. int main() {
  54. print_impl<int8_t>("int8_t");
  55. print_impl<int16_t>("int16_t");
  56. print_impl<int32_t>("int32_t");
  57. print_impl<int64_t>("int64_t");
  58.  
  59. print<56>();
  60. print<-128>();
  61. print<9832586235>();
  62. }
Success #stdin #stdout 0s 2832KB
stdin
Standard input is empty
stdout
int8_t: a
int16_t: s
int32_t: i
int64_t: x
56: a
-128: a
9832586235: x