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).
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.
Enum ClassC++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped.
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
Explanation: Enumeration (enum) is a user defined data type in C. It is used to assign names to integral constants.
How about simply use one of the enum values? e.g.:
//...
enum
{
UNKNOWN,
STARTED,
STOPPED
};
private:
using Type = decltype( UNKNOWN );
//...
[live demo]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With