简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM