]>
Commit | Line | Data |
---|---|---|
1e59de90 TL |
1 | // Copyright 2020 Peter Dimov |
2 | // Distributed under the Boost Software License, Version 1.0. | |
3 | // https://www.boost.org/LICENSE_1_0.txt | |
4 | ||
5 | #include <boost/describe.hpp> | |
6 | #include <boost/mp11.hpp> | |
7 | #include <stdexcept> | |
8 | #include <typeinfo> | |
9 | #include <string> | |
10 | #include <cstring> | |
11 | ||
12 | [[noreturn]] void throw_invalid_name( char const * name, char const * type ) | |
13 | { | |
14 | throw std::runtime_error( | |
15 | std::string( "Invalid enumerator name '" ) + name | |
16 | + "' for enum type '" + type + "'" ); | |
17 | } | |
18 | ||
19 | template<class E> E string_to_enum( char const * name ) | |
20 | { | |
21 | bool found = false; | |
22 | E r = {}; | |
23 | ||
24 | boost::mp11::mp_for_each< boost::describe::describe_enumerators<E> >([&](auto D){ | |
25 | ||
26 | if( !found && std::strcmp( D.name, name ) == 0 ) | |
27 | { | |
28 | found = true; | |
29 | r = D.value; | |
30 | } | |
31 | ||
32 | }); | |
33 | ||
34 | if( found ) | |
35 | { | |
36 | return r; | |
37 | } | |
38 | else | |
39 | { | |
40 | throw_invalid_name( name, typeid( E ).name() ); | |
41 | } | |
42 | } | |
43 | ||
44 | #include <iostream> | |
45 | ||
46 | BOOST_DEFINE_ENUM(E, v1, v2, v3) | |
47 | ||
48 | int main() | |
49 | { | |
50 | try | |
51 | { | |
52 | std::cout << "v1: " << string_to_enum<E>( "v1" ) << std::endl; | |
53 | std::cout << "v2: " << string_to_enum<E>( "v2" ) << std::endl; | |
54 | std::cout << "v3: " << string_to_enum<E>( "v3" ) << std::endl; | |
55 | std::cout << "v4: " << string_to_enum<E>( "v4" ) << std::endl; | |
56 | } | |
57 | catch( std::exception const & x ) | |
58 | { | |
59 | std::cout << x.what() << std::endl; | |
60 | } | |
61 | } |