C++ 切片整数参数包
我有一个类,它获取一个整数参数包C++ 切片整数参数包,c++,c++17,variadic-templates,template-meta-programming,C++,C++17,Variadic Templates,Template Meta Programming,我有一个类,它获取一个整数参数包[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>...> std::tuple 我也愿意接受其他
[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>...>
std::tuple,/*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
}
模板
结构{
std::tuple,/*RemoveLast*/Ints>…>t;
};
int main(){
S a;
标准:get(a.t)[0][0]=42;
//解释:
//a.t是元组
//get(a.t)是数组
//get(a.t)[0]是数组
//get(a.t)[0][0]为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, "!" );
}
#包括
#包括
#包括
#包括
模板
自动常量表达式条(标准::索引\u序列常量&)
{返回
std::tuple<
std::数组<
std::数组,
std::tuple\u元素\u t::value>。。。
>{}; }
模板
自动constexpr foo()
{返回条
(std::make_index_sequence{});}
int main()
{
constexpr auto f=foo();
使用typeTuple=std::tuple<
std::数组,
std::数组,
std::数组,
std::array>;
静态断言(std::is_same::value,“!”;
}
我不是在寻找成对的数组。我正在寻找一个2-d阵列的集合,我认为这是非常不同的。@Baruch-对不起,我不明白你到底想要什么;请你加个例子好吗?我加了个例子。我希望如此clarifies@Baruch-好的。如果我正确理解了您的要求,修改后的答案应该可以使用。@Baruch-answer稍微简化了一点(不再是getVal()
;元组作为类型传递,不再作为值传递)。