• Saves Valuable Time
  • Trusted Accuracy for 12 Years
  • 15-Day Money-Back Guarantee

C++ Equivalent to Java Enums

Simple enums in Java have simple equivalents in C++:

Java C++
public enum Simple
{
    FOO,
    BAR
}
enum class Simple
{
    FOO,
    BAR
};

More complex enums in Java unfortunately have exceedingly complex equivalents in C++:

Java C++
public enum Complex
{
    FOO("Foo"),
    BAR("Bar");

    private final String value;

    Complex(String enumValue)
    {
        this.value = enumValue;
    }

    public void InstanceMethod()
    {
        //...
    }
}
#include <string>
#include <vector>

class Complex final
{
public:
    static Complex FOO(L"FOO", InnerEnum::FOO, L"Foo");
    static Complex BAR(L"BAR", InnerEnum::BAR, L"Bar");

private:
    static std::vector<Complex> valueList;

    class StaticConstructor
    {
    public:
        StaticConstructor()
        {
            valueList.push_back(FOO);
            valueList.push_back(BAR);
        }
    };

    static StaticConstructor staticConstructor;

public:
    enum class InnerEnum
    {
        FOO,
        BAR
    };

    const InnerEnum innerEnumValue;
private:
    const std::wstring nameValue;
    const int ordinalValue;
    static int nextOrdinal = 0;

    const std::wstring value;

public:
    Complex(const std::wstring &name, InnerEnum innerEnum, const std::wstring &enumValue) : nameValue(name), ordinalValue(nextOrdinal++), innerEnumValue(innerEnum)
    {
        this->value = enumValue;
    }

    virtual void InstanceMethod()
    {
        //...
    }

    bool operator == (const Complex &other)
    {
        return this->ordinalValue == other.ordinalValue;
    }

    bool operator != (const Complex &other)
    {
        return this->ordinalValue != other.ordinalValue;
    }

    static std::vector<Complex> values()
    {
        return valueList;
    }

    int ordinal()
    {
        return ordinalValue;
    }

    std::wstring toString()
    {
        return nameValue;
    }

    static Complex valueOf(const std::wstring &name)
    {
        for (auto enumInstance : Complex::valueList)
        {
            if (enumInstance.nameValue == name)
            {
                return enumInstance;
            }
        }
    }
};


Use Java to C++ Converter to convert from Java to C++.     

Additional resource: Java and C++ Equivalents


Copyright © 1997 – 2017 Tangible Software Solutions Inc.