#include "enum.h"
#include <iostream>
#include <assert.h>
BETTER_ENUM(Word, int, Hello, World)
BETTER_ENUM(Channel, int, Cyan = 1, Magenta, Yellow, Black)
BETTER_ENUM(Channel2, int, Red, Green, Blue)
// We will create a map from this function:
constexpr const char* describe(Channel2 channel)
{
switch (channel) {
case Channel2::Red: return "the red channel";
case Channel2::Green: return "the green channel";
case Channel2::Blue: return "the blue channel";
}
return "needed for gcc 5";
}
void selfValue() {
// Here is the map. The actual type is better_enums::map<Channel2, const char*>.
constexpr auto descriptions = better_enums::make_map(describe);
std::cout << descriptions[Channel2::Red] << std::endl;
std::cout << descriptions.from_enum(Channel2::Red) << std::endl;
std::cout << descriptions.to_enum("the green channel") << std::endl;
auto not_a_literal = std::string("the blue channel");
std::cout << descriptions.to_enum(not_a_literal.c_str()) << std::endl;
}
void test() {
//test();
std::cout << (+Word::Hello)._to_string() << ", "
<< (+Word::World)._to_string() << "!"
<< std::endl;
// There are three functions:
//
// 1. ._to_string
// 2. ::_from_string
// 3. ::_from_string_nothrow
// 1. ::_from_string_nocase
// 2. ::_from_string_nocase_nothrow
Channel channel = Channel::Cyan;
std::cout << channel._to_string() << " ";
channel = Channel::_from_string("Magenta");
std::cout << channel._to_string() << " ";
better_enums::optional<Channel> maybe_channel =
Channel::_from_string_nothrow("Yellow");
if (!maybe_channel)
std::cout << "error";
else
std::cout << maybe_channel->_to_string() << " ";
channel = Channel::_from_string_nocase("cYaN");
channel = Channel::_from_integral(2);
channel = Channel::_from_integral_unchecked(0);
std::cout << channel._to_integral() << " ";
// check
assert(Channel::_is_valid(3));
assert(Channel::_is_valid("Magenta"));
assert(Channel::_is_valid_nocase("cYaN"));
// Iteration
for (size_t index = 0; index < Channel::_size(); ++index) {
const char* name = Channel::_names()[index];
Channel channel = Channel::_values()[index];
std::cout << channel._to_integral() << " ";
}
// 自定义字符串映射
selfValue();
std::cout << +Channel2::Red << std::endl;
//Channel2::_size() Channel2::_name()
}
//C++20
#include <iostream>
#include <string>
#include <type_traits>
// C++20反射假设
template <typename T>
std::string enumToString(T e) {
// 假设有一个名为getEnumName的反射函数
return getEnumName(e);
}
// 示例枚举
enum class MyEnum {
Value1,
Value2,
Value3,
};
int main() {
MyEnum myValue = MyEnum::Value2;
std::cout << "Enum as string: " << enumToString(myValue) << std::endl;
return 0;
}
GitHub - aantron/better-enums: C++ compile-time enum to string, iteration, in a single header file