Advertisement
Guest User

Untitled

a guest
Jul 8th, 2012
385
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #define assert(_)
  2. namespace helper {
  3.     template<char...> struct toInt;
  4.     template<> struct toInt<> { enum {value = 0, log=1, valid = true}; };
  5.     template<char h, char... t> struct toInt<h, t...> {
  6.         typedef toInt<t...> tail;
  7.         enum { i = h-'0',
  8.                log = tail::log*10,
  9.                value = i*tail::log + tail::value,
  10.                valid = tail::valid && (unsigned(i) < 10)
  11.         };
  12.     };
  13. }
  14.  
  15.  
  16. class month_t {
  17.     int m;
  18.     month_t(int m) : m{m} { }
  19. public:
  20.     operator int() { return m; }
  21.     static month_t fromInt(int m) { assert(m >= 1 && m <= 12); return {m}; }
  22. };
  23.  
  24. class day_t {
  25.     int d;
  26.     day_t(int d) : d{d} { }
  27. public:
  28.     operator int() { return d; }
  29.     static day_t fromInt(int d) { assert(d >= 1 && d <= 31); return {d}; }
  30. };
  31.  
  32. template <char... a> month_t operator "" _month() {
  33.         enum { m = helper::toInt<a...>::value  };
  34.         static_assert(helper::toInt<a...>::valid && m >= 1 && m <= 12, "Invalid month");
  35.         return month_t::fromInt(m);
  36. };
  37. template <char... a> day_t operator "" _day() {
  38.         enum { m = helper::toInt<a...>::value  };
  39.         static_assert(helper::toInt<a...>::valid && m >= 1 && m <= 31, "Invalid day");
  40.         return day_t::fromInt(m);
  41. };
  42.  
  43.  
  44. #include <iostream>
  45. void setBirthDay( day_t d, month_t m) {
  46.     std::cout << d << "/" << m  << std::endl;  
  47. }
  48.  
  49. int main() {
  50.     setBirthDay( 9_day , 7_month  );
  51.  //   setBirthDay( 39_day , 7_month  ); //error: static_assert failed "Invalid day"
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement