将 std::tuple 转换为 std::array C++11 [英] Convert std::tuple to std::array C++11
问题描述
如果我有 std::tuple
(其中类型是同类的),是否有一个股票函数或构造函数可以转换为 std::array<;双>
?
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>
?
:我能够使用递归模板代码(我在下面发布的草稿答案)使其工作.这是处理这个问题的最好方法吗?似乎会有一个库存功能......或者如果你对我的答案有改进,我会很感激.我不会回答这个问题(毕竟,我想要一个好的方式,而不仅仅是一个可行的方式),并且更愿意选择其他人的[希望更好]的答案.
: 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::tuple 转换为 std::array C++11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!