Last active
September 7, 2017 07:17
-
-
Save simgt/6027839 to your computer and use it in GitHub Desktop.
Simple example of how to enumerate an enum's values (preprocessor + boost.spirit)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <boost/spirit/include/qi.hpp> | |
| #include <boost/spirit/include/phoenix_core.hpp> | |
| #include <boost/spirit/include/phoenix_operator.hpp> | |
| #include <boost/spirit/include/phoenix_stl.hpp> | |
| #include <iostream> | |
| #include <vector> | |
| #include <string> | |
| std::vector<std::string> parse_enum(const std::string enum_str) { | |
| namespace spirit = boost::spirit; | |
| namespace qi = spirit::qi; | |
| namespace nix = boost::phoenix; | |
| std::vector<std::string> vec; | |
| qi::rule<std::string::const_iterator, std::string(), qi::space_type> value | |
| = +qi::alnum; // \todo take assignments into account | |
| bool r = qi::phrase_parse( | |
| enum_str.begin(), | |
| enum_str.end(), | |
| qi::lit("enum") >> +qi::alnum >> '{' | |
| >> value[nix::push_back(nix::ref(vec), qi::_1)] % ',' | |
| >> -qi::char_(',') | |
| >> '}', | |
| qi::space | |
| ); | |
| return vec; | |
| } | |
| // __VA_ARGS__ is used to allow comas in the enum definition | |
| #define REFLEXIVE_ENUM(NAME, ...) \ | |
| const std::vector<std::string> ValuesOf##NAME = parse_enum(#__VA_ARGS__); \ | |
| __VA_ARGS__; | |
| // EXAMPLE: | |
| REFLEXIVE_ENUM(Foo, // the values will be put in a vector named ValuesOfFoo | |
| enum Foo { | |
| Bjarn, | |
| Douglas, | |
| Harry | |
| }; | |
| ); | |
| int main() { | |
| std::vector<std::string>::const_iterator it; | |
| for (it = ValuesOfFoo.begin(); it != ValuesOfFoo.end(); it++) | |
| std::cout << *it << std::endl; | |
| Foo bar = Douglas; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment