Advertisement
zhangsongcui

Compare Operators

Feb 24th, 2012
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | None | 0 0
  1. #include <cstdio>
  2. #include <functional>
  3. //#include <cstdint>  codepad doesn't recognize it
  4. #include <stdint.h>
  5.  
  6. #if __cplusplus >= 201103L
  7. #   define CONSTEXPR constexpr
  8. #else
  9. #   define CONSTEXPR
  10. #endif
  11.  
  12. namespace System
  13. {
  14.     template <typename Type, template <typename> class Oper>
  15.     struct CmpResult {
  16.         CONSTEXPR CmpResult(Type v, bool r): value(v), last_cmp_res(r) {}
  17. #if __cplusplus >= 201103L
  18.         constexpr explicit operator bool() const {
  19.             return this->last_cmp_res;
  20.         }
  21. #else
  22.         operator void *() const {
  23.             return reinterpret_cast<void *>(this->last_cmp_res);
  24.         }
  25. #endif
  26.  
  27.         Type value;
  28.         bool last_cmp_res;
  29.  
  30.     private:
  31. #if __cplusplus >= 201103L
  32.         CmpResult& operator =(const CmpResult&) = delete;
  33. #else
  34.         CmpResult& operator =(const CmpResult&);
  35. #endif
  36.     };
  37.  
  38.     template <typename Type>
  39.     struct ValueType
  40.     {
  41.         CONSTEXPR ValueType(Type val): value(val) {}
  42. #define DECL_OPER(op, op_type)\
  43. CONSTEXPR friend CmpResult<ValueType, op_type> operator op(ValueType left, ValueType right) {\
  44.     return CmpResult<ValueType, op_type>(right, left.value op right.value);\
  45. }\
  46. CONSTEXPR friend CmpResult<ValueType, op_type> operator op(CmpResult<ValueType, op_type> left, ValueType right) {\
  47.     return left ? CmpResult<ValueType, op_type>(right, bool(left.value op right.value)) : CmpResult<ValueType, op_type>(0, false);\
  48. }
  49.         DECL_OPER(<, std::less)
  50.         DECL_OPER(<=, std::less)
  51.         DECL_OPER(>, std::greater)
  52.         DECL_OPER(>=, std::greater)
  53. #undef DECL_OPER
  54.  
  55.         Type value;
  56.     };
  57.     typedef ValueType<int8_t> SByte;
  58.     typedef ValueType<uint8_t> Byte;
  59.     typedef ValueType<int16_t> Int16;
  60.     typedef ValueType<uint16_t> UInt16;
  61.     typedef ValueType<int32_t> Int32;
  62.     typedef ValueType<uint32_t> UInt32;
  63.     typedef ValueType<int64_t> Int64;
  64.     typedef ValueType<uint64_t> UInt64;
  65.     typedef ValueType<float> Single;
  66.     typedef ValueType<double> Double;
  67. }
  68.  
  69. int main()
  70. {
  71.     using namespace std;
  72.     using namespace System;
  73.     Single d = 5;
  74.     if (3 < d <= 6.5f)
  75.         std::puts("true");
  76.     else
  77.         std::puts("false");
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement