Skip to content

Instantly share code, notes, and snippets.

@usagi
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usagi/0093be0daffd796afef4 to your computer and use it in GitHub Desktop.
Save usagi/0093be0daffd796afef4 to your computer and use it in GitHub Desktop.
#pragma once
#include <string>
#include <stdexcept>
#include <boost/preprocessor.hpp>
// WRP_MAKE_ENUM の内部で switch-case の case を生成するための補助マクロ
#define WRP_MAKE_ENUM_TO_STRING_ELEMENT( r, data, elem ) \
case data :: elem : return BOOST_PP_STRINGIZE( elem ); \
// enum class _symbol_name : _base_type { enumerators }; と to_string( const _symbol_name ) を生成するためのマクロ
#define WRP_MAKE_ENUM( _symbol_name, _base_type, enumerators ) \
enum class _symbol_name \
: _base_type \
{ BOOST_PP_SEQ_ENUM( enumerators ) \
}; \
\
template < typename T = void > \
inline auto to_string( const _symbol_name value ) \
-> std::string \
{ \
switch ( value ) \
{ \
BOOST_PP_SEQ_FOR_EACH( \
WRP_MAKE_ENUM_TO_STRING_ELEMENT, \
_symbol_name, \
enumerators \
) \
default: throw std::runtime_error( "undefined enum member" );\
} \
} \
#include <iostream>
#include <cstdint>
#include "enum.hxx"
namespace abc
{
WRP_MAKE_ENUM
( def
, std::uint8_t
, ( ppp )
( qqq )
( rrr )
)
}
auto main()
-> int
{
std::cout
<< to_string( abc::def::ppp ) << "\n"
<< to_string( abc::def::qqq ) << "\n"
<< to_string( abc::def::rrr ) << "\n"
;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment