Doubles/ints模板函数的向量 [英] Vector of doubles/ints template function
问题描述
我有一个要概括的功能.简而言之,我有一个 std :: string s
,我使用解析器对其进行处理,生成一个 std :: vector< std :: string>
(这是一个列表,如"1、2、3"
),该函数应返回 std :: vector< T>
,其中 T
限于double
或 int
.
I have a function that I'd like to generalize. Simply put, I have a std::string s
that I process with a parser generating a std::vector<std::string>
(it's a list as in "1, 2, 3"
), and the function should return a std::vector<T>
, with T
restricted to double
or int
.
向量应包含转换后的值.
The vector should contain the transformed values.
我受困于 std :: transform
的最后一个参数,因为它应该在 std :: stod
和 std :: stoi
.我要寻找的解决方案是使用模板元编程魔术,而不是使用 if(std :: is_same< T,int> :: value)
.
I am stuck with the last parameter of std::transform
, as it should switch between std::stod
and std::stoi
. The solution I am looking for is with template metaprogramming magic, not with if (std::is_same<T,int>::value)
.
有任何提示吗?
template <class T>
auto get_vector(std::string s) -> std::vector<T>
{
std::vector<T> v;
auto tmp = split(s);
std::transform(tmp.begin(), tmp.end(), std::back_inserter(v), ??);
return v;
}
推荐答案
您可以做的一件事是利用 stringstream
和 lambda 并具有 stringstream
为您完成转换.像
One thing you could do is utilize a stringstream
and a lambda and have the stringstream
do the conversion for you. Something like
std::transform(tmp.begin(), tmp.end(), std::back_inserter(v),
[](const std::string& elem) -> T
{
std::stringstream ss(elem);
T value;
ss >> value;
return value;
});
这篇关于Doubles/ints模板函数的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!