1.10
enum.h
1/*
2 * Copyright (C) 2018 Microchip Technology Inc. All rights reserved.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6#ifndef EGT_DETAIL_ENUM_H
7#define EGT_DETAIL_ENUM_H
8
14#include <cstring>
15#include <stdexcept>
16#include <string>
17#include <utility>
18
19namespace egt
20{
21inline namespace v1
22{
23namespace detail
24{
25
46template<class T>
48{
50 static const std::pair<T, char const*> data[];
51};
52
54template<class T>
55constexpr const char* enum_to_string(T const& e)
56{
57 for (const auto& i : EnumStrings<T>::data)
58 if (i.first == e)
59 return i.second;
60
61 throw std::runtime_error("invalid enum");
62}
63
65template<class T>
66constexpr T enum_from_string(const char* value)
67{
68 for (const auto& i : EnumStrings<T>::data)
69 if (std::strcmp(i.second, value) == 0)
70 return i.first;
71
72 throw std::runtime_error("invalid enum string");
73}
74
76template<class T>
77constexpr T enum_from_string(const std::string& value)
78{
79 for (const auto& i : EnumStrings<T>::data)
80 if (i.second == value)
81 return i.first;
82
83 throw std::runtime_error("invalid enum string");
84}
85
86}
87}
88}
89
90#endif
constexpr T enum_from_string(const char *value)
Convert a string to an enum value.
Definition enum.h:66
constexpr const char * enum_to_string(T const &e)
Convert an enum to a string.
Definition enum.h:55
EGT framework namespace.
Definition animation.h:24
When using enum_to_string() and enum_from_string(), this type needs to be defined and specialized to ...
Definition enum.h:48
static const std::pair< T, char const * > data[]
Enum string conversion map.
Definition enum.h:50