I've written a code reading csv file using fold expressions. The only thing that should be defined is columns types and file name:
template <typename ...T, std::size_t... Is>
void parseLineToTuple(std::tuple<T...>& empty, const std::string& line, std::index_sequence<Is...>)
{
std::stringstream ss(line);
(ss >> ... >> std::get<Is>(empty));
}
template <typename ... T>
std::vector<std::tuple<T...>> readTuples(const std::string& fileName)
{
std::vector<std::tuple<T...>> lines;
std::ifstream file(fileName);
if (file.is_open())
{
std::string line;
while (getline(file, line))
{
std::tuple<T...> empty;
parseLineToTuple(empty, line, std::make_index_sequence<sizeof...(T)>());
lines.push_back(empty);
}
}
return lines;
}
To use it:
auto content = readTuples<std::string, int, double>("lines.csv");
lines.csv:
apple, 20, 10.54
orange, 30, 4.5
Is it possible to get index sequence another way than passing it to a method and get the received parameter type? If so I would get rid of the parseLineToTuple method