Skip to content

Instantly share code, notes, and snippets.

@simgt
Last active September 7, 2017 07:17
Show Gist options
  • Select an option

  • Save simgt/6027839 to your computer and use it in GitHub Desktop.

Select an option

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)
#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