转换的std ::元组到std ::阵列C ++ 11 [英] Convert std::tuple to std::array C++11
问题描述
如果我有的std ::元组LT;双,双,双>
(其中类型是均一的),有一个股票的功能或构造转换为的std ::阵列<双>
?
If I have std::tuple<double, double, double>
(where the type is homogeneous), is there a stock function or constructor to convert to std::array<double>
?
编辑::我能得到它递归模板code(我的回答下面草案公布)工作。这是处理最好的方法?看起来会有一个股票功能,为这个...或者,如果你有改进,我的回答,我会AP preciate它。我会留下未回答此问题(毕竟,我要的好的方式,不只是一个可行的方法),并且将preFER选择别人的[希望更好]的答案。
: I was able to get it working with recursive template code (my draft answer posted below). Is this the best way to handle this? It seems like there would be a stock function for this... Or if you have improvements to my answer, I'd appreciate it. I'll leave the question unanswered (after all, I want a good way, not just a workable way), and would prefer to select someone else's [hopefully better] answer.
谢谢你的建议。
推荐答案
转换一个元组数组未做使用递归,包括使用完美的转发(仅适用于移动类型有用):
Converting a tuple to an array without making use of recursion, including use of perfect-forwarding (useful for move-only types):
#include <iostream>
#include <tuple>
#include <array>
template<int... Indices>
struct indices {
using next = indices<Indices..., sizeof...(Indices)>;
};
template<int Size>
struct build_indices {
using type = typename build_indices<Size - 1>::type::next;
};
template<>
struct build_indices<0> {
using type = indices<>;
};
template<typename T>
using Bare = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
template<typename Tuple>
constexpr
typename build_indices<std::tuple_size<Bare<Tuple>>::value>::type
make_indices()
{ return {}; }
template<typename Tuple, int... Indices>
std::array<
typename std::tuple_element<0, Bare<Tuple>>::type,
std::tuple_size<Bare<Tuple>>::value
>
to_array(Tuple&& tuple, indices<Indices...>)
{
using std::get;
return {{ get<Indices>(std::forward<Tuple>(tuple))... }};
}
template<typename Tuple>
auto to_array(Tuple&& tuple)
-> decltype( to_array(std::declval<Tuple>(), make_indices<Tuple>()) )
{
return to_array(std::forward<Tuple>(tuple), make_indices<Tuple>());
}
int main() {
std::tuple<double, double, double> tup(1.5, 2.5, 4.5);
auto arr = to_array(tup);
for (double x : arr)
std::cout << x << " ";
std::cout << std::endl;
return 0;
}
这篇关于转换的std ::元组到std ::阵列C ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!