我有以下冗长的代码:
struct thing1 { int key, std::string value; };
struct thing2 { int key, std::string value; };
// ...
struct thingN { int key, std::string value; };
struct thing_map {
thing1 t1;
thing2 t2;
// ...
thingN tN;
std::string get(int key) {
if(t1.key == key) return t1.value;
if(t2.key == key) return t2.value;
// ...
if(tN.key == key) return tN.value;
throw std::runtime_error("bad key");
}
};
我可以重构这些thing
,使它们成为一个std::tuple<thing1, thing2, /* ... */ thingN>
,这样我就可以用有类型的std::get
访问它们,因此不会失去任何功能(即std::get<thing1>(things)
)。但是我无法想出如何实现if
级联。互联网上有多种将函数应用于每个元组元素的函数实现,但是这些函数始终使用索引参数包来执行映射,因此我无法选择单个元素并返回其值。可能要做的琐碎事情是将tN.value
保存到一个捕获变量中并返回它,但我觉得有更好的解决方案。
为了清晰起见,我要做的是:
struct thing_map {
std::tuple<thing1, thing2, /* ... */ thingN> things;
std::string get(int key) {
foreach(auto&& thing : things) {
if (key == thing.key) return thing.value;
}
throw std::runtime_error("bad key");
}
};
我正在使用C++17