Skip to content

Commit 65da24f

Browse files
committed
fixup! Add program_options example with a generic custom validator for enums
1 parent ed655e2 commit 65da24f

File tree

2 files changed

+12
-18
lines changed

2 files changed

+12
-18
lines changed

example/program_options.cpp

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,7 @@ enum class log_level {
2626

2727
BOOST_DESCRIBE_ENUM(log_level, fatal, error, warning, trace)
2828

29-
template <typename E, typename = std::enable_if_t<std::is_enum<E>::value>>
30-
std::ostream& operator<<(std::ostream& os, E e)
31-
{
32-
boost::mp11::mp_for_each< boost::describe::describe_enumerators<E> >([&](auto D) {
33-
if( e == D.value ) os << D.name;
34-
});
35-
36-
return os;
37-
}
29+
using boost::describe::operators::operator<<;
3830

3931
// Generic program_options custom validator for (described) enums
4032
template <
@@ -57,16 +49,8 @@ void validate(boost::any& v,
5749
const std::string& name = validators::get_single_string(values);
5850

5951
// Convert string to enum
60-
bool found = false;
6152
E r = {};
62-
63-
boost::mp11::mp_for_each<Ed>([&](auto D){
64-
if( !found && std::strcmp( D.name, name.c_str() ) == 0 )
65-
{
66-
found = true;
67-
r = D.value;
68-
}
69-
});
53+
bool found = boost::describe::enum_from_string(name.c_str(), r);
7054

7155
if (found)
7256
v = boost::any(r);

include/boost/describe/operators.hpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,16 @@ template<class T, class Ch, class Tr> std::enable_if_t<
160160
return os;
161161
}
162162

163+
template <typename E, typename = std::enable_if_t<has_describe_enumerators<E>::value>>
164+
std::ostream& operator<<(std::ostream& os, E e)
165+
{
166+
boost::mp11::mp_for_each< boost::describe::describe_enumerators<E> >([&](auto D) {
167+
if( e == D.value ) os << D.name;
168+
});
169+
170+
return os;
171+
}
172+
163173
} // namespace operators
164174

165175
} // namespace describe

0 commit comments

Comments
 (0)