enum_from_string.hpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #ifndef BOOST_DESCRIBE_ENUM_FROM_STRING_HPP_INCLUDED
  2. #define BOOST_DESCRIBE_ENUM_FROM_STRING_HPP_INCLUDED
  3. // Copyright 2020, 2021 Peter Dimov
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // https://www.boost.org/LICENSE_1_0.txt
  6. #include <boost/describe/detail/config.hpp>
  7. #if defined(BOOST_DESCRIBE_CXX14)
  8. #include <boost/describe/enumerators.hpp>
  9. #include <boost/mp11/algorithm.hpp>
  10. #include <cstring>
  11. #include <type_traits>
  12. #if defined(_MSC_VER) && _MSC_VER == 1900
  13. # pragma warning(push)
  14. # pragma warning(disable: 4100) // unreferenced formal parameter
  15. #endif
  16. namespace boost
  17. {
  18. namespace describe
  19. {
  20. template<class E, class De = describe_enumerators<E>>
  21. bool enum_from_string( char const* name, E& e ) noexcept
  22. {
  23. bool found = false;
  24. mp11::mp_for_each<De>([&](auto D){
  25. if( !found && std::strcmp( D.name, name ) == 0 )
  26. {
  27. found = true;
  28. e = D.value;
  29. }
  30. });
  31. return found;
  32. }
  33. template<class S, class E, class De = describe_enumerators<E>,
  34. class En = std::enable_if_t<
  35. std::is_same<typename S::value_type, char>::value &&
  36. std::is_same<typename S::traits_type::char_type, char>::value
  37. >
  38. >
  39. bool enum_from_string( S const& name, E& e ) noexcept
  40. {
  41. bool found = false;
  42. mp11::mp_for_each<De>([&](auto D){
  43. if( !found && name == D.name )
  44. {
  45. found = true;
  46. e = D.value;
  47. }
  48. });
  49. return found;
  50. }
  51. } // namespace describe
  52. } // namespace boost
  53. #if defined(_MSC_VER) && _MSC_VER == 1900
  54. # pragma warning(pop)
  55. #endif
  56. #endif // defined(BOOST_DESCRIBE_CXX14)
  57. #endif // #ifndef BOOST_DESCRIBE_ENUM_FROM_STRING_HPP_INCLUDED