gpt4 book ai didi

c++ - 将 std::tuple 转换为 std::array C++11

转载 作者:IT老高 更新时间:2023-10-28 21:59:34 25 4
gpt4 key购买 nike

如果我有 std::tuple<double, double, double> (其中类型是同质的),是否有股票函数或构造函数转换为std::array<double> ?

编辑::我能够使用递归模板代码(我的答案草稿发布在下面)。这是处理这个问题的最好方法吗?似乎会有一个股票功能......或者如果你对我的回答有改进,我会很感激。我不会回答这个问题(毕竟,我想要一个的方法,而不仅仅是一个可行的方法),并且更愿意选择其他人的[希望更好的]答案。

感谢您的建议。

最佳答案

在不使用递归的情况下将元组转换为数组,包括使用完美转发(对仅移动类型有用):

#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;
}

关于c++ - 将 std::tuple 转换为 std::array C++11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10604794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com