optional.qbk 2.31 KB
[#optional]
[section optional]

[h1 Synopsis]

  template <class P, class Default = /* unspecified */>
  struct optional;

This is a [link parser_combinator parser combinator].

[table Arguments
  [[Name]   [Type]]
  [[`P`]    [[link parser parser]]]
  [[`Default`] [[link metaprogramming_value template metaprogramming value]]]
]

[h1 Description]

It tries parsing the input with `P`. When `P` succeeds, the result of parsing is
the result of `P`. Otherwise no characters are consumed and the result of
parsing is `Default`.

[h1 Header]

  #include <boost/metaparse/optional.hpp>

[h1 Expression semantics]

For any `p` [link parser parser] and `d`
[link metaprogramming_value template metaprogramming value]

  optional<p, d>

is equivalent to

  one_of<p, return_<d>>

[h1 Example]

  #include <boost/metaparse/optional.hpp>
  #include <boost/metaparse/start.hpp>
  #include <boost/metaparse/int_.hpp>
  #include <boost/metaparse/middle_of.hpp>
  #include <boost/metaparse/sequence.hpp>
  #include <boost/metaparse/lit_c.hpp>
  #include <boost/metaparse/string.hpp>
  #include <boost/metaparse/get_result.hpp>

  #include <boost/mpl/int.hpp>
  #include <boost/mpl/equal.hpp>
  #include <boost/mpl/equal_to.hpp>
  #include <boost/mpl/vector_c.hpp>
  
  using namespace boost::metaparse;
  
  using complex_number =
    sequence<
      // Real
      int_,

      // Imaginary
      optional<
        middle_of<lit_c<'+'>, int_, lit_c<'i'>>,
        boost::mpl::int_<0>
      >
    >
  ;
  
  static_assert(
    boost::mpl::equal<
      boost::mpl::vector_c<int, 1, 0>,
      get_result<
        complex_number::apply<BOOST_METAPARSE_STRING("1"), start>
      >::type,

      boost::mpl::equal_to<boost::mpl::_, boost::mpl::_>
    >::type::value,
    "No imaginary"
  );

  static_assert(
    boost::mpl::equal<
      boost::mpl::vector_c<int, 1, 0>,
      get_result<
        complex_number::apply<BOOST_METAPARSE_STRING("1+0i"), start>
      >::type,

      boost::mpl::equal_to<boost::mpl::_, boost::mpl::_>
    >::type::value,
    "0 as imaginary"
  );

  static_assert(
    boost::mpl::equal<
      boost::mpl::vector_c<int, 0, 1>,
      get_result<
        complex_number::apply<BOOST_METAPARSE_STRING("0+1i"), start>
      >::type,

      boost::mpl::equal_to<boost::mpl::_, boost::mpl::_>
    >::type::value,
    "Non-null imaginary"
  );

[endsect]