fork(7) download
  1. template <typename T, typename U>
  2. constexpr inline bool CanTypeRepresentValue(const U value) {
  3. return ((value > U()) == (static_cast<T>(value) > T())) &&
  4. (value == static_cast<U>(static_cast<T>(value)));
  5. }
  6.  
  7. #include <cmath>
  8. #include <iostream>
  9. #include <limits>
  10.  
  11. template <typename T>
  12. class Number {
  13. T rep;
  14. public:
  15. constexpr Number(T t = T()) : rep(t) {}
  16. constexpr operator T () const { return rep; }
  17. };
  18.  
  19. int main(int argc, char **argv) {
  20. #define TEST(type, value) static_assert(CanTypeRepresentValue<type>(value), #type " can't represent " #value)
  21. #define FAIL(type, value) static_assert(!CanTypeRepresentValue<type>(value), #type " can represent " #value)
  22. TEST(int, std::numeric_limits<int>::max());
  23. FAIL(int, unsigned(std::numeric_limits<int>::max()) + 1);
  24. TEST(unsigned, std::numeric_limits<int>::max());
  25. FAIL(unsigned, -3);
  26. TEST(char,122ULL);
  27. FAIL(char,256ULL);
  28. TEST(int,2.0f);
  29. FAIL(char,3.1415926535);
  30. TEST(Number<int>,250LL);
  31. TEST(Number<long>,-3.0);
  32. FAIL(Number<int>,2.1);
  33. FAIL(Number<char>,3.1415926535);
  34. #undef TEST
  35. #undef FAIL
  36.  
  37. #define CanTypeFitValue CanTypeRepresentValue
  38.  
  39. long long value;
  40. while(std::cin >> value) {
  41. std::cout << value << ": ";
  42. std::cout << CanTypeFitValue<int8_t>(value) << " ";
  43. std::cout << CanTypeFitValue<uint8_t>(value) << " ";
  44. std::cout << CanTypeFitValue<int16_t>(value) << " ";
  45. std::cout << CanTypeFitValue<uint16_t>(value) << " ";
  46. std::cout << CanTypeFitValue<int32_t>(value) << " ";
  47. std::cout << CanTypeFitValue<uint32_t>(value) << " ";
  48. std::cout << CanTypeFitValue<int64_t>(value) << " ";
  49. std::cout << CanTypeFitValue<uint64_t>(value) << std::endl;
  50. }
  51.  
  52. }
  53.  
Success #stdin #stdout 0s 2900KB
stdin
6 1203032847 2394857 -13423 9324 -192992929
stdout
6: 1 1 1 1 1 1 1 1
1203032847: 0 0 0 0 1 1 1 1
2394857: 0 0 0 0 1 1 1 1
-13423: 0 0 1 0 1 0 1 0
9324: 0 0 1 1 1 1 1 1
-192992929: 0 0 0 0 1 0 1 0