Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

2. The text to parse

With Metaparse you can create template metaprograms parsing an input text. To pass the input text to the metaprograms, you need to represent them as types. For example let's represent the text "Hello world" as a type. The most straightforward way of doing it would be creating a variadic template class taking the characters of the text as template arguments:

template <char... Cs>
struct string;

The text "11 + 2" can be represented the following way:

string<'1', '1', ' ', '+', ' ', '2'>

Metaparse provides this type for you. Run the following command in Metashell:

> #include <boost/metaparse/string.hpp>
[Note] Note

Note that the > character at the beginning of the above code example is the prompt of Metashell. It is added to the code examples as a hint to what you should run in Metashell (or add to your test cpp file if you are using a regular development environment).

[Note] Note

Note that in the online-demo of Metashell you can paste code into the shell by right-clicking on the shell somewhere and choosing Paste from browser in the context menu.

This will make this type available for you. Now you can try running the following command:

> boost::metaparse::string<'1', '1', ' ', '+', ' ', '2'>

The shell will echo (almost) the same type back to you. The only difference is that it is in a sub-namespace indicating the version of Metaparse being used.

The nice thing about this representation is that metaprograms can easily access the individual characters of the text. The not so nice thing about this representation is that if you want to write the text "Hello world" in your source code, you have to type a lot.

Metaparse provides a macro that can turn a string literal into an instance of boost::metaparse::string. This is the BOOST_METAPARSE_STRING macro. You get it by including <boost/metaparse/string.hpp>. Let's try it by running the following command in Metashell:

> BOOST_METAPARSE_STRING("11 + 2")

You will get the same result as you got by instantiating boost::metaparse::string yourself.


PrevUpHomeNext