使用可变参数模板构建元组 [英] build tuple using variadic templates
问题描述
因此,我在C ++ 11之前编写了一些代码,这些代码根据模板参数解析字符串。我不想使用可变参数模板来为每个数量的参数定义一个定义,但是我无法集中精力正确初始化元组。看到我想要的简化代码,这是2个参数的特殊情况:
So I have some code written before C++11 that parses a string based on template arguments. Instead of having one definition for each number of arguments I would like to use variadic templates, but I can't wrap my head around how to initialize a tuple correctly. See this simplified code of what I want, this is for the special case of 2 arguments:
template <typename Arg1, typename Arg2>
struct parser
{
static tuple<Arg1, Arg2> parse(const string& str)
{
Arg1 arg1;
Arg2 arg2;
// do the parsing with for example stringstream
return tuple<Arg1, Arg2>(arg1, arg2);
}
};
在可变参数情况下,将元组中的参数放入元组中存在问题。我可以使用以下方法构造返回值持有人:
I'm having problem with putting the arguments in the tuple in the variadic case. I can construct the return value holder with:
tuple<Args...> retVal;
但我不知道是否有一种方法可以遍历参数并将它们放在元组。我已经看到了一些递归魔术,例如可以使用 printf
函数,但是我不知道它是否可以应用于这种情况。
but I don't know if there is a way to iterate through the arguments and put them in a tuple. I've seen some recursive magic to get for example the printf
functions, but I don't know if it could apply to this case.
推荐答案
您不需要帮助程序类。
You don't need a helper class. Do it with functions instead.
template <typename T> std::tuple<T> parse(std::istream& is)
{
T t; is >> t;
return std::tuple<T>(std::move(t));
}
template <typename T, typename Arg, typename... Args>
std::tuple<T, Arg, Args...> parse(std::istream& is)
{
T t; is >> t;
return std::tuple_cat(std::tuple<T>(std::move(t)),
parse<Arg, Args...>(is));
}
template <typename... Args>
std::tuple<Args...> parse(const std::string& str)
{
std::istringstream is(str);
return parse<Args...>(is);
}
编辑:今天,我知道了通过使用扩展以非常简单的方式完成此操作:
EDIT: Today, I got the idea how to do it in a very simple way with the use of the expansion:
template <typename T> T read(std::istream& is)
{
T t; is >> t; return t;
}
template <typename... Args>
std::tuple<Args...> parse(std::istream& is)
{
return std::make_tuple(read<Args>(is)...);
}
template <typename... Args>
std::tuple<Args...> parse(const std::string& str)
{
std::istringstream is(str);
return parse<Args...>(is);
}
这篇关于使用可变参数模板构建元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!