Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a real enum class in C++

Tags:

c++

enums

c++11

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).

like image 621
nyarlathotep108 Avatar asked Sep 01 '17 17:09

nyarlathotep108


People also ask

How is enum implemented in C?

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.

Does C have enum class?

Enum ClassC++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped.

Can I declare enum in class?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

What is true enum?

Explanation: Enumeration (enum) is a user defined data type in C. It is used to assign names to integral constants.


1 Answers

How about simply use one of the enum values? e.g.:

//...
enum
{
    UNKNOWN,
    STARTED,
    STOPPED
};

private:

using Type = decltype( UNKNOWN );
//...

[live demo]

like image 101
W.F. Avatar answered Oct 20 '22 18:10

W.F.