exp*_*t3r 2 c++ enums templates
我正在尝试为与结构中不同枚举值对应的不同类型的变量创建查找。
这是我到目前为止的解决方案:
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;
}
};
Run Code Online (Sandbox Code Playgroud)
我正在寻找更优雅的解决方案,因为在我的实际项目中,我的结构中有许多不同的变量,因此 if/else 块变得非常大。
像这样的事情,也许:
template<MYENUM TYPE>
auto& GetAttribute() {
return std::get<int(TYPE)>(std::tie(x, y, z));
}
Run Code Online (Sandbox Code Playgroud)
(你本质上是在重新发明std::tuple。)