【发布时间】:2020-01-31 18:21:32
【问题描述】:
我正在编写一个 CSV 解析器,我认为将一些高级 C++ 付诸实践是个好主意。特别是,有一个有用的功能可以在给定分隔符的情况下拆分 CSV 文件的一行。虽然它是一个简单的函数,但现在我希望该函数返回一个具有不同数量的参数和类型的元组。例如:
int main() {
auto [a, b, c] = extract<int, std::string, float>("42;hello;3.1415", ';');
std::cout << a << ' ' << b << ' ' << c << std::endl;
}
应该打印出来:
42 hello 3.1415
于是我想到了一个可变参数模板函数:
template <typename... T>
std::tuple<T...> extract(const std::string&& str, const char&& delimiter) {
std::tuple<T...> splited_line;
/* ... */
return splited_line;
}
但我不能使用可变参数修改该函数内部的元组,如下所示:
std::get<i>(splited_line) // doesn't work
这并不奇怪,我对这种语言还很陌生。我现在想知道如何以优雅的方式实现这个小功能。
感谢您的帮助。
【问题讨论】:
-
extract的现有参数应该是正常的引用。&&在这里什么也做不了。顺便说一句:第 1 步:使用std::apply将元组中的每个值通过引用 传递给template<typename ...Args> void helper(const std::string& str, const char& delimiter, Args & ...args)。第 2 步:使用基本可变参数包技术实现helper()进行提取。虽然通常在 stackoverflow.com 上,我们不会从头开始为其他人编写整个程序,但需要业力的人可能会这样做...... -
谢谢,我去试试!我不是要求一个完整的计划,而是更多像你这样的指导方针;)
标签: c++ variadic-templates variadic-functions stdtuple