0

In Java, I can work with enums like classes. For example, I can create enum's constructor that take a value and init enum's value and class static function values() to list all enum's values.

How to implement this in C++?

Here is the Java code:

enum EquationType {

    LINE("LINE"), LINE3D("LINE3D"), BEZIER("BEZIER"), PLANE("PLANE");

    EquationType(String curve_type) {

        type = curve_type;

    } //END: CurveType()

    String type; // enum's member variable that store symbolic name of type (for utilite using)

    public String get_type_string() {

        return type;

    } //END: get_type_string()

    public static EquationType _bystring(String type) throws Exception {

        for (EquationType value : values()) { // search by list of enum's values

            if (value.get_type_string().equals(type.trim().toUpperCase())) {

                return value;

            }
        }

    } //END: _bystring()

} //END: enum EquationType

It creates enum with 4 members (LINE, LINE3D, BEZIER, PLANE). This enum class type have the function that return the enum's type by the string name value like EquationType._bystring("PLANE") will return EquationType.PLANE. It uses the values() function that lists all possible enum type values.

Is there some analog in C++?

4
  • Can you please fix the formatting? Commented Feb 9, 2020 at 5:47
  • I have my doubts as to whether that compiles in Java. Did you define a type called string? Commented Feb 9, 2020 at 5:49
  • 3
    There is no exact equivalent in C++, but there are several pretty close alternatives. In some cases an enum class will work. In this case, a full-fledged class, with some overloaded operators will probably be a closer match. In any case, unfortunately, stackoverflow.com is not a replacement for a good C++ book, and you should find complete information about doing this in any good C++ book. Commented Feb 9, 2020 at 5:49
  • 2
    So you want to get the enum value via a string and vice versa? std::unordered_map? In this case maybe you don't want to use enum at all. Commented Feb 9, 2020 at 5:51

1 Answer 1

0
#include <string>
#include <unordered_map>

enum EquationType {
  LINE, LINE3D, BEZIER, PLANE
};

int main() {
  std::unordered_map<std::string, EquationType> equationMap({
    {"LINE", LINE},
    {"LINE3D", LINE3D},
    {"BEZIER", BEZIER},
    {"PLANE", PLANE}
  });

  EquationType line = equationMap["LINE"];
}

Disclaimer: I haven't compiled this. I may have messed up the syntax.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.