【发布时间】:2019-04-20 16:16:47
【问题描述】:
我有以下详细代码:
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");
}
};
我可以将things 重构为std::tuple<thing1, thing2, /* ... */ thingN>,这允许我使用键入的std::get 访问它们,因此不会丢失任何功能(即std::get<thing1>(things))。我不知道如何实现if 级联。有多种函数实现将函数应用于 Internet 上的每个元组元素,但这些函数总是使用索引参数包进行映射,因此我无法选择单个元素并返回其值。要做的微不足道的事情可能是将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
【问题讨论】:
-
C++11、C++14 还是 C++17?
-
既然thingN类型都一样,为什么会有不同的类型?如果它们至少有一个共同的基类,您可以使用它来循环,而不是为每个元素使用不同的不相关类型。
-
这只是一个人为的例子,不同的东西实际上是不同的。 @max66 C++17,编辑到帖子中。
-
如果你使用的所有“事物”都有一个共同的关键变量,我真的不明白为什么你不能用关键变量创建一个父类,然后列出指向父类的指针;这样,无论您找到的东西属于哪个子类,您都可以检查键值。
-
@Barnack,你失去了价值语义。在每件事都不同的情况下,您可能还会失去返回确切值类型的能力。这些指针还必须指向存储在某个稳定位置的东西。
标签: c++ templates c++17 stdtuple