“解压”用可变参数模板调用函数的数组 [英] "Unpack" an array to call a function with variadic template

查看:97
本文介绍了“解压”用可变参数模板调用函数的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ben strasser C ++快速csv解析器: https:// github.com/ben-strasser/fast-cpp-csv-parser 。它使用可变参数模板将列值传递回处理csv数据的while循环:

I'm using the ben strasser C++ fast csv parser: https://github.com/ben-strasser/fast-cpp-csv-parser. It uses a variadic template to pass column values back to the while loop that processes the csv data:

io::CSVReader<2> in(csv_filename);
double x, y;
while(in.read_row(x,y)) {
    //code with x and y
}

这会在CSVReader类中调用以下函数:

This calls the following function in the CSVReader class:

template<class ...ColType>
bool read_row(ColType& ...cols){
    //snip
}

对于我的x和y值,这对我来说很好用。但是,我想将此扩展为使用任意尺寸。这意味着我的数据需要读取(已知)列数。我想使用这样的东西:

This works fine for me with my x and y values. However, I would like to expand this to use arbitrary dimensions. This means my data has a (known) number of columns I need to read. I would like to use something like this:

io::CSVReader<known_dimension> in(csvfname);
double data[known_dimension];
while(in.read_row(data)) {
    //code with data[0],data[1],...,data[known_number]
}

但是,这不是有效的语法。我需要将双精度数组拆包为指向双精度指标的单独参数。我想在不修改快速csv解析器的情况下执行此操作。

However, this is not valid syntax. I need to "unpack" the array of doubles into separate arguments of pointers to my doubles. I'd like to do this without modifications to the fast csv parser.

推荐答案

您可以使用 std :: integer_sequence 为此目的:

You can use std::integer_sequence for that purpose:

namespace Detail
{
template <typename Reader, typename T, std::size_t... I>
void read_row(Reader& in, T* data, std::index_sequence<I...>)
{
     in.read_row(data[I]...); // A trick here
} 

}

template <std::size_t N, typename T>
void read_row(io::CSVReader<N>& in, T* data)
{
     Detail::read_row(in, data, std::make_index_sequence<N>{});
} 

当然,可以这样使用:

int a[7];
io::CSVReader<7> r;
read_row(r, a);

正在工作示例:链接

对于以下编译器C ++ 14- integer_sequence (实际上只需要 index_sequence )就很容易实现:

For compiler "below" C++14 - integer_sequence (actually just index_sequence needed) is pretty easy to implement:

template <std::size_t... I>
class index_sequence {};

make_index_sequence 并不是那么容易-而且可行的:

And make_index_sequence not so easy - but also doable:

template <std::size_t N, std::size_t ...I>
struct make_index_sequence : make_index_sequence<N-1, N-1,I...> {};

template <std::size_t ...I>
struct make_index_sequence<0,I...> : index_sequence<I...> {};

这篇关于“解压”用可变参数模板调用函数的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆