boost_no_cxx11_user_lit.ipp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // (C) Copyright John Maddock 2013
  2. // Use, modification and distribution are subject to the
  3. // Boost Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. // See http://www.boost.org/libs/config for more information.
  6. // MACRO: BOOST_NO_CXX11_USER_DEFINED_LITERALS
  7. // TITLE: C++11 user defined literals.
  8. // DESCRIPTION: The compiler does not support the C++11 literals including user-defined suffixes.
  9. #include <memory>
  10. namespace boost_no_cxx11_user_defined_literals {
  11. struct my_literal
  12. {
  13. my_literal() : val(0) {}
  14. my_literal(int i) : val(i) {}
  15. my_literal(const my_literal& a) : val(a.val) {}
  16. bool operator==(const my_literal& a) const { return val == a.val; }
  17. int val;
  18. };
  19. template <unsigned base, unsigned long long val, char... Digits>
  20. struct parse_int
  21. {
  22. // The default specialization is also the termination condition:
  23. // it gets invoked only when sizeof...Digits == 0.
  24. static_assert(base<=16u,"only support up to hexadecimal");
  25. static constexpr unsigned long long value{ val };
  26. };
  27. template <unsigned base, unsigned long long val, char c, char... Digits>
  28. struct parse_int<base, val, c, Digits...>
  29. {
  30. static constexpr unsigned long long char_value = (c >= '0' && c <= '9')
  31. ? c - '0'
  32. : (c >= 'a' && c <= 'f')
  33. ? c - 'a'
  34. : (c >= 'A' && c <= 'F')
  35. ? c - 'A'
  36. : 400u;
  37. static_assert(char_value < base, "Encountered a digit out of range");
  38. static constexpr unsigned long long value{ parse_int<base, val * base +
  39. char_value, Digits...>::value };
  40. };
  41. my_literal operator "" _suf1(unsigned long long v)
  42. {
  43. return my_literal(v);
  44. }
  45. template <char...PACK>
  46. my_literal operator "" _bin()
  47. {
  48. return parse_int<2, 0, PACK...>::value;
  49. }
  50. int test()
  51. {
  52. my_literal a = 0x23_suf1;
  53. my_literal b = 1001_bin;
  54. return ((a == my_literal(0x23)) && (b == my_literal(9))) ? 0 : 1;
  55. }
  56. }