I am trying to implement an enum class
that behaves like the one introduced with C++11 (with type safety etc.) but that also behaves as a real class (with constructor, method, etc.). In order to do so, I kept the internal enum
anonymous: this had the side effect that in order to keep m_value
as a private
member variable, I had to add a static
member variable named _
, as you can see below:
#include <iostream>
#include <experimental/string_view>
class State
{
public:
static enum
{
UNKNOWN,
STARTED,
STOPPED
} _;
private:
using Type = decltype( _ );
Type m_value;
public:
constexpr State( Type value = UNKNOWN )
: m_value( value )
{ }
constexpr bool operator==( Type value ) const
{
return m_value == value;
}
constexpr std::experimental::string_view to_string( ) const
{
switch ( m_value )
{
case UNKNOWN: return "UNKNOWN";
case STARTED: return "STARTED";
case STOPPED: return "STOPPED";
}
return "";
}
};
State::Type State::_;
int main( )
{
State state;
std::cout << state.to_string( ) << std::endl;
state = State::STARTED;
std::cout << state.to_string( ) << std::endl;
if( state == State::STOPPED )
{
std::cout << state.to_string( ) << std::endl;
}
return 0;
}
Is there a way to get rid of the useless static
member variable _
? I would like to keep the internal enum
anonymous, and somehow to fetch its type when required (= only privately).
Aucun commentaire:
Enregistrer un commentaire