简体   繁体   English

将枚举转换为成员变量 [问题] C++

[英]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.我正在寻找更优雅的解决方案,因为在我的实际项目中,我的结构中有许多不同的变量,因此 if/else 块变得非常大。

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 .) (您实际上是在重新发明std::tuple 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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