gpt4 book ai didi

c++ - 切片整数参数包

转载 作者:太空狗 更新时间:2023-10-29 21:09:34 26 4
gpt4 key购买 nike

我有一个获取整数参数包的类 [a,b,...,y,z]。我需要将它扩展成两个包 [a,...,y][b,...,z] - 第一次和一次删除最后。最终产品应该是一堆二维数组,大小为 [a,b][b,c] 等,直到 [x, y],[y,z]。我正在尝试使用这样的东西:

std::tuple< std::array< std::array< int, /*RemoveFirst*/Ints>, /*RemoveLast*/Ints>...>

我也对其他解决方案持开放态度。

示例:

template <int... Ints>
struct S {
std::tuple< std::array< std::array< int, /*RemoveFirst*/Ints>, /*RemoveLast*/Ints>...> t;
};
int main() {
S<2,3,4> a;
std::get<0>(a.t)[0][0] = 42;
// explenation:
// a.t is tuple<array<array<int,3>,2>,array<array<int,4>,3>>
// get<0>(a.t) is array<array<int,3>,2>
// get<0>(a.t)[0] is array<int,3>
// get<0>(a.t)[0][0] is int
}

最佳答案

我提出以下代码

#include <array>
#include <tuple>
#include <utility>
#include <type_traits>

template <typename T, std::size_t ... Is>
auto constexpr bar (std::index_sequence<Is...> const &)
{ return
std::tuple<
std::array<
std::array<int,
std::tuple_element_t<Is+1u, T>::value>,
std::tuple_element_t<Is, T>::value>...
>{}; }

template <std::size_t ... Is>
auto constexpr foo ()
{ return bar<std::tuple<std::integral_constant<std::size_t, Is>...>>
(std::make_index_sequence<sizeof...(Is)-1u>{}); }

int main ()
{
constexpr auto f = foo<2u, 3u, 5u, 7u, 11u>();

using typeTuple = std::tuple<
std::array<std::array<int, 3u>, 2u>,
std::array<std::array<int, 5u>, 3u>,
std::array<std::array<int, 7u>, 5u>,
std::array<std::array<int, 11u>, 7u>>;

static_assert( std::is_same<typeTuple const, decltype(f)>::value, "!" );
}

关于c++ - 切片整数参数包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58049650/

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