fork download
  1. #include <iostream>
  2.  
  3. template<int UB, int US>
  4. struct Unit { // a unit in the SI/IEEE systems
  5. enum { B=UB, s=US }; // bytes and seconds
  6. };
  7.  
  8. template<typename Unit> // a magnitude with a unit
  9. struct Value {
  10. double val; // the magnitude
  11. explicit constexpr Value(double d) : val{d} {}
  12. Value operator+(const Value& x) {
  13. return Value{val + x.val};
  14. }
  15. };
  16.  
  17. using Byte = Unit<1, 0>; // unit: byte
  18. using MemBlock = Value<Byte>; // shortcut
  19.  
  20. constexpr Value<Byte> operator"" _B(long double d) {
  21. return Value<Byte>{d};
  22. }
  23.  
  24. constexpr Value<Byte> operator"" _kB(long double d) {
  25. return Value<Byte>{d * 1024};
  26. }
  27.  
  28. constexpr Value<Byte> operator"" _MB(long double d) {
  29. return Value<Byte>{d * 1024 * 1024};
  30. }
  31.  
  32. constexpr double n_B(const Value<Byte>& b) { // free functions to be simple
  33. return b.val;
  34. }
  35.  
  36. constexpr double n_kB(const Value<Byte>& b) {
  37. return b.val / 1024;
  38. }
  39.  
  40. constexpr double n_MB(const Value<Byte>& b) {
  41. return b.val / 1024 / 1024;
  42. }
  43.  
  44. // Let's add something useful to the example
  45. using Second = Unit<0, 1>; // unit: sec.
  46. // using Second2 = Unit<0, 2>; // s^2
  47. using Time = Value<Second>; // time in seconds by default
  48. using TransferRate = Value<Unit<1, -1>>; // bytes/second type
  49.  
  50. constexpr Value<Second> operator"" _s(long double d) {
  51. return Value<Second>{d};
  52. }
  53.  
  54. constexpr double n_s(const Value<Second>& s) {
  55. return s.val;
  56. }
  57.  
  58. constexpr TransferRate operator/(const MemBlock& m, const Time& t) {
  59. return TransferRate{n_B(m) / n_s(t)};
  60. }
  61.  
  62. int main() {
  63. MemBlock a = 1024.0_B;
  64. //MemBlock b = 3.0; // NOT OK! unit needed
  65. auto b = 3.0_kB; // OK
  66. auto c = a + b;
  67. std::cout << n_kB(a) << "+" << n_kB(b)
  68. << " = " << n_kB(c) << '\n'; // or define your operator<<()
  69.  
  70. // Another example..
  71. TransferRate slow = c / 1.0_s;
  72. auto fast = slow + slow;
  73. // etc..
  74. }
  75.  
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
1+3 = 4