add to_underlying traits function

This commit is contained in:
2019-11-22 03:10:30 +07:00
parent 9efae8b856
commit e488de0d46
2 changed files with 31 additions and 4 deletions

View File

@@ -8,6 +8,7 @@
#include <stdexcept>
#include <string_view>
#include <type_traits>
namespace enum_hpp
{
@@ -96,7 +97,7 @@ namespace enum_hpp::detail
enum Enum : Type {\
ENUM_HPP_GENERATE_ENUM_FIELDS(Fields)\
};\
ENUM_HPP_TRAITS_IMPL(Enum, Type, Fields)
ENUM_HPP_TRAITS_DECL(Enum, Fields)
//
// ENUM_HPP_CLASS_DECL
@@ -106,21 +107,26 @@ namespace enum_hpp::detail
enum class Enum : Type {\
ENUM_HPP_GENERATE_ENUM_FIELDS(Fields)\
};\
ENUM_HPP_TRAITS_IMPL(Enum, Type, Fields)
ENUM_HPP_TRAITS_DECL(Enum, Fields)
//
// ENUM_HPP_TRAITS_IMPL
// ENUM_HPP_TRAITS_DECL
//
#define ENUM_HPP_TRAITS_IMPL(Enum, Type, Fields)\
#define ENUM_HPP_TRAITS_DECL(Enum, Fields)\
struct Enum##_traits {\
private:\
enum enum_names_for_this_score_ { ENUM_HPP_GENERATE_ENUM_FIELDS(Fields) };\
public:\
using underlying_t = std::underlying_type_t<Enum>;\
static constexpr std::size_t size = ENUM_HPP_PP_SEQ_SIZE(Fields);\
static constexpr const Enum values[] = { ENUM_HPP_GENERATE_VALUES(Enum, Fields) };\
static constexpr const std::string_view names[] = { ENUM_HPP_GENERATE_NAMES(Fields) };\
public:\
static constexpr underlying_t to_underlying(Enum e) noexcept {\
return static_cast<underlying_t>(e);\
}\
\
static constexpr std::string_view to_string(Enum e) noexcept {\
for ( std::size_t i = 0; i < size; ++i) {\
if ( e == values[i] ) {\

View File

@@ -107,6 +107,27 @@ TEST_CASE("enum") {
}
}
SECTION("to_underlying") {
{
STATIC_REQUIRE(sn::color_traits::to_underlying(sn::color::red) == enum_to_underlying(sn::color::red));
STATIC_REQUIRE(sn::color_traits::to_underlying(sn::color::green) == enum_to_underlying(sn::color::green));
STATIC_REQUIRE(sn::color_traits::to_underlying(sn::color::blue) == enum_to_underlying(sn::color::blue));
STATIC_REQUIRE(sn::color_traits::to_underlying(sn::color(42)) == 42);
}
{
STATIC_REQUIRE(sn::render::mask_traits::to_underlying(sn::render::mask::none) == enum_to_underlying(sn::render::mask::none));
STATIC_REQUIRE(sn::render::mask_traits::to_underlying(sn::render::mask::color) == enum_to_underlying(sn::render::mask::color));
STATIC_REQUIRE(sn::render::mask_traits::to_underlying(sn::render::mask::alpha) == enum_to_underlying(sn::render::mask::alpha));
STATIC_REQUIRE(sn::render::mask_traits::to_underlying(sn::render::mask::all) == enum_to_underlying(sn::render::mask::all));
}
{
STATIC_REQUIRE(sn::numbers_traits::to_underlying(sn::_0) == enum_to_underlying(sn::_0));
STATIC_REQUIRE(sn::numbers_traits::to_underlying(sn::_180) == enum_to_underlying(sn::_180));
STATIC_REQUIRE(sn::numbers_traits::to_underlying(sn::_240) == enum_to_underlying(sn::_240));
STATIC_REQUIRE(sn::numbers_traits::to_underlying(sn::numbers(100500)) == 100500);
}
}
SECTION("to_string") {
{
STATIC_REQUIRE(sn::color_traits::to_string(sn::color::red) == "red");