I want to write a function with the following signature (or similar):
template <typename... Ts>
void collection_to_csv(const std::string filepath, const Ts& ... containers);
The function should write a csv file to a file located at filepath, where containers can be any number of iteratable containers from the STD and would define the columns of the outputted CSV file. E.g. I could use it like this:
std::vector<int> column1{1, 2, 3, 4};
std::list<float> column2{1.5, 2.5, 3.5, 4.5};
collections_to_csv(someFilePath, c1, c2);
Is this possible? So far I've been trying to use variadic templates like so:
template <typename... Ts>
void collection_to_csv(const std::string filepath, std::initializer_list<std::string> headers, const Ts& ... containers)
{
std::ofstream file;
file.open(filepath, std::ofstream::out | std::ofstream::trunc);
for (std::size_t irow=0; irow < size; ++irow)
{
for (const auto& container : containers) //But how to iterate through the variadic arguments when they could be different types?
{
file << container[i] << ",";
}
}
file.flush();
file.close();
}
Everything I've seen about variadic templates suggests they're 'iterated' using recursion but this would force a 'column first' iteration order. I need a 'row first' order, making me think variadic templates might be the wrong tool here. Is there a better approach?