【发布时间】:2018-06-26 16:09:09
【问题描述】:
我有一个字符串向量,每个字符串都是将 std::to_string 应用于某些基本数据类型(例如 char、int、double)的结果。我想要一个函数将其撤消为适当类型的元组。
我有一个简单的函数模板来反转 std::to_string:
template<typename T>
T from_string(std::string s)
{
}
template<>
int from_string<int>(std::string s)
{
return std::stoi(s);
}
template<>
double from_string<double>(std::string s)
{
return std::stod(s);
}
//... and more such specializations for the other basic types
我想要一个类似的函数:
template<typename... Ts>
std::tuple<Ts> undo(const std::vector<std::string>>& vec_of_str)
{
// somehow call the appropriate specializations of from_string to the elements of vector_of_str and pack the results in a tuple. then return the tuple.
}
函数的行为应该是这样的:
int main()
{
auto ss = std::vector<std::string>>({"4", "0.5"});
auto tuple1 = undo<int, double>(ss);
std::tuple<int, double> tuple2(4, 0.5);
// tuple1 and tuple2 should be identical.
}
我想我必须对Ts中的参数进行“迭代”(或许正确的说法是“解包”),调用前面的函数,from_string对每一个,然后将from_string每次应用的结果打包成一个元组。我已经看到(并使用过)解包模板参数包的示例 - 它们通常是递归的(但不是以函数调用自身的通常方式),但我不知道如何做其余的事情。
【问题讨论】:
-
您必须知道原始类型是什么。这听起来像是一个 XY 问题。
-
您将不得不解析字符串以确定它所代表的数据类型(例如是
int还是float或double)。 -
我编辑了代码以表示解释字符串所需的类型被指定为函数撤消的模板参数。这是否解决了您的担忧?
-
遗憾的是,元组完全是编译时解析的结构,而向量是运行时的。不可能从任意长度的向量生成任意元组。另一方面,如果向量是从元组类型构造的,并且您仍然可以访问该类型,则可以将相同的值填充回该特定元组类型的实例中。
标签: c++ templates variadic-templates variadic-functions variadic