optional.qbk 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. [#optional]
  2. [section optional]
  3. [h1 Synopsis]
  4. template <class P, class Default = /* unspecified */>
  5. struct optional;
  6. This is a [link parser_combinator parser combinator].
  7. [table Arguments
  8. [[Name] [Type]]
  9. [[`P`] [[link parser parser]]]
  10. [[`Default`] [[link metaprogramming_value template metaprogramming value]]]
  11. ]
  12. [h1 Description]
  13. It tries parsing the input with `P`. When `P` succeeds, the result of parsing is
  14. the result of `P`. Otherwise no characters are consumed and the result of
  15. parsing is `Default`.
  16. [h1 Header]
  17. #include <boost/metaparse/optional.hpp>
  18. [h1 Expression semantics]
  19. For any `p` [link parser parser] and `d`
  20. [link metaprogramming_value template metaprogramming value]
  21. optional<p, d>
  22. is equivalent to
  23. one_of<p, return_<d>>
  24. [h1 Example]
  25. #include <boost/metaparse/optional.hpp>
  26. #include <boost/metaparse/start.hpp>
  27. #include <boost/metaparse/int_.hpp>
  28. #include <boost/metaparse/middle_of.hpp>
  29. #include <boost/metaparse/sequence.hpp>
  30. #include <boost/metaparse/lit_c.hpp>
  31. #include <boost/metaparse/string.hpp>
  32. #include <boost/metaparse/get_result.hpp>
  33. #include <boost/mpl/int.hpp>
  34. #include <boost/mpl/equal.hpp>
  35. #include <boost/mpl/equal_to.hpp>
  36. #include <boost/mpl/vector_c.hpp>
  37. using namespace boost::metaparse;
  38. using complex_number =
  39. sequence<
  40. // Real
  41. int_,
  42. // Imaginary
  43. optional<
  44. middle_of<lit_c<'+'>, int_, lit_c<'i'>>,
  45. boost::mpl::int_<0>
  46. >
  47. >
  48. ;
  49. static_assert(
  50. boost::mpl::equal<
  51. boost::mpl::vector_c<int, 1, 0>,
  52. get_result<
  53. complex_number::apply<BOOST_METAPARSE_STRING("1"), start>
  54. >::type,
  55. boost::mpl::equal_to<boost::mpl::_, boost::mpl::_>
  56. >::type::value,
  57. "No imaginary"
  58. );
  59. static_assert(
  60. boost::mpl::equal<
  61. boost::mpl::vector_c<int, 1, 0>,
  62. get_result<
  63. complex_number::apply<BOOST_METAPARSE_STRING("1+0i"), start>
  64. >::type,
  65. boost::mpl::equal_to<boost::mpl::_, boost::mpl::_>
  66. >::type::value,
  67. "0 as imaginary"
  68. );
  69. static_assert(
  70. boost::mpl::equal<
  71. boost::mpl::vector_c<int, 0, 1>,
  72. get_result<
  73. complex_number::apply<BOOST_METAPARSE_STRING("0+1i"), start>
  74. >::type,
  75. boost::mpl::equal_to<boost::mpl::_, boost::mpl::_>
  76. >::type::value,
  77. "Non-null imaginary"
  78. );
  79. [endsect]