我有一个元组,我想对传递索引处的元组中的类型执行某些操作(在示例中,打印默认值)。目前,我让它调用一个函数来增加模板化索引,直到它等于运行时索引。由于这种方法会降低性能,有更好的方法吗?
这是示例的代码:
#include <tuple>
#include <vector>
#include <string>
#include <iostream>
using tup = std::tuple<int, std::string, double, int>;
template <size_t Index = 0>
void constexpr PrintDefaultAtTupleIndex(size_t i)
{
if (Index == i)
{
std::cout << "\"" << std::tuple_element_t<Index, tup>() << "\"" << std::endl;
return;
}
if constexpr (Index + 1 < std::tuple_size_v<tup>)
return PrintDefaultAtTupleIndex<Index + 1>(i);
}
int main()
{
std::vector<size_t> indexs = {0, 3, 8, 2, 1};
for (size_t &i : indexs)
{
PrintDefaultAtTupleIndex(i);
}
}
Run Code Online (Sandbox Code Playgroud)
这是真实代码的简化示例。真正的代码是元组的格式化程序。我试图有一种方法来指定它的打印顺序,所以我让它将索引存储在元组和格式化程序(input_formats)中,然后我通过它们调用OutputInputFormat.