创建派生自可变参数模板包的类型元组

Creating tuple of types derived from Variadic Template Pack

本文关键字:类型 元组 参数 派生 变参 创建      更新时间:2023-10-16

给定一个size_t值的列表作为可变参数模板参数包,如何根据参数包制作派生类型(例如矩阵(的元组,这样,可变参数的第n个元素就会生成Matrix<n, n+1>。例如:

make_matrix_tuple<2,3,4,5>() == make_tuple( Matrix<2,3>, Matrix<3,4>, Matrix<4,5> );

如何在size_t的参数包中编写make_matrix_tuple函数?

派生的类型我指的不是继承,而是依赖(?我不确定正确的术语是什么。
解包参数包非常简单

template <typename ElementType, size_t... Sizes>
void make_tuple_of_vectors() { std::tuple < std::array<ElementType, Sizes> ... > tuple; }

但是,我相信在下一部分时,我有点过头了。 我试图递归地从参数包中解压缩一对参数,如下所示:

template <typename Type, size_t size1, size_t size2>
struct dummy_matrix
{
size_t SIZE1 = size1;
size_t SIZE2 = size2;
using type = Type;
};
template <size_t Iterator, typename ElementType, size_t T, size_t... Sizes>
struct unpack_two
{
using type = typename unpack_two<Iterator - 1, ElementType, Sizes...>::type;
};
template<typename ElementType, size_t T, size_t T2, size_t... Sizes>
struct unpack_two<0, ElementType, T, T2, Sizes...>
{ 
using type = dummy_matrix<ElementType, T, T2>;
};

因此,unpack_two<N, Type, Sizes...>::type给出了第 N 个和第 (N+1( 个矩阵类型。
有了这个,我被困在对我来说似乎合理的东西上,但编译器不同意。

template <size_t... Sizes, size_t... Is>
auto
foo_impl(std::index_sequence<Is...>) {
std::tuple < unpack_two<Is, float, Sizes ... >::type ... > tuple; 
return tuple; 
}
template <size_t... Args>
void foo()
{
auto vs = foo_impl<Args...>(std::make_index_sequence<sizeof...(Args)-1>{});
}
int main() { foo<6,9,12>(); }

我正在尝试解压缩unpack_two模板的std::size_t大小列表,然后解压缩std::index_sequencestd::make_tuple()
我将不胜感激解释为什么我的尝试失败了,甚至是这里std::index_sequence正确的工具。但我最感兴趣的是解决所提出的问题的任何解决方案。

如何

根据参数包制作派生类型(例如矩阵(的元组,以便可变参数的第n个元素生成Matrix<n, n+1>[?

也许在帮助程序函数中使用constexprstd::array

一个例子

#include <array>
#include <tuple>
#include <utility>
template <std::size_t, std::size_t>
struct Matrix
{ };
template <std::size_t ... Ds, std::size_t ... Is>
auto mmt_helper (std::index_sequence<Is...>)
{
constexpr std::array ca { Ds... };
return std::make_tuple(Matrix<ca[Is], ca[Is+1u]>{}...);
}
template <std::size_t ... Ds>
auto make_matrix_tuple ()
{ return mmt_helper<Ds...>(std::make_index_sequence<sizeof...(Ds)-1>{}); }
int main ()
{
auto mt = make_matrix_tuple<2,3,4,5>();
using T1 = decltype(mt);
using T2 = std::tuple<Matrix<2u, 3u>, Matrix<3u, 4u>, Matrix<4u, 5u>>;
static_assert( std::is_same_v<T1, T2> );
}