Converting an enum to a member variable [PROBLEM] C++

Viewed 54

I am trying to create a lookup for variables of different types corresponding to different enum values within a struct.

Here is the solution I have so far:

struct X {
    int x;
    std::string y;
    char z;
    enum class MYENUM {
        X, Y, Z
    };
    template<MYENUM TYPE>
    auto& GetAttribute() {
        if constexpr (TYPE == MYENUM::X) return x;
        else if constexpr (TYPE == MYENUM::Y) return y;
        else if constexpr (TYPE == MYENUM::Z) return z;
    }
};

I am in search for a more elegant solution, as in my actual project, I have many different variables within my struct, and thus the if/else block becomes very large.

1 Answers

Something like this, perhaps:

template<MYENUM TYPE>
auto& GetAttribute() {
    return std::get<int(TYPE)>(std::tie(x, y, z));
}

Demo

(You are essentially reinventing std::tuple.)

Related