Ron*_*Ron 5 c++ templates stdtuple c++17
我有以下详细代码:
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");
}
};
Run Code Online (Sandbox Code Playgroud)
我可以将things 重构为 an std::tuple<thing1, thing2, /* ... */ thingN>,这允许我使用 typed 访问它们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");
}
};
Run Code Online (Sandbox Code Playgroud)
我正在使用 C++17
您可以使用 C++17,因此我建议使用std::apply()模板折叠,如下所示
std::string get(int key)
{
return std::apply([&](auto const & ... args)
{
std::string ret;
( ((key == args.key) ? (ret = args.value, true) : false)
|| ... || (throw std::runtime_error("bad key"), false) );
return ret;
}, things);
}
Run Code Online (Sandbox Code Playgroud)
以下是完整的编译示例
#include <tuple>
#include <string>
#include <iostream>
#include <stdexcept>
struct thing1 { int key{1}; std::string value{"one"}; };
struct thing2 { int key{2}; std::string value{"two"}; };
struct thing3 { int key{3}; std::string value{"three"}; };
struct thing4 { int key{4}; std::string value{"four"}; };
struct thing_map
{
std::tuple<thing1, thing2, thing3, thing4> things;
std::string get(int key)
{
return std::apply([&](auto const & ... args)
{
std::string ret;
( ((key == args.key) ? (ret = args.value, true) : false)
|| ... || (throw std::runtime_error("bad key"), false) );
return ret;
}, things);
}
};
int main ()
{
thing_map tm;
std::cout << tm.get(1) << std::endl;
std::cout << tm.get(2) << std::endl;
std::cout << tm.get(3) << std::endl;
std::cout << tm.get(4) << std::endl;
std::cout << tm.get(5) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)