如何创建一个固定类型的元组,其大小在 C++17 的编译时已知?

How to create a tuple of fix types whose size is a known at compile time in C++17?

我想创建一个通用元素类型的元组类型,其长度在编译时已知。例如,如果我有

static constexpr const std::size_t compiletime_size = 2;

using tuple_int_size_2 = magic (int, compiletime_size);

tuple_int_size_2 应与 std::tuple<int, int>

类型相同

这可以通过递归来完成:

#include <tuple>

template <size_t N, typename Head, typename... T>
struct magic {
    using tuple_type = typename magic<N - 1, Head, Head, T...>::tuple_type;
};

template <typename... T>
struct magic<1, T...> {
    using tuple_type = std::tuple<T...>;
};

int main()
{
    auto t = typename magic<3, int>::tuple_type{};
    return 0;
}

不过,我想知道 std::array 是否是解决您要解决的任何任务的更简单直接的解决方案。

没有递归,有两个声明的(未定义的)辅助函数和一个 using

template <typename T, std::size_t ... Is>
constexpr auto gft_helper (std::index_sequence<Is...> const &)
   -> decltype(std::make_tuple( ((void)Is, std::declval<T>())... ));

template <typename T, std::size_t N>
constexpr auto get_fixed_tuple ()
  -> decltype(gft_helper<T>(std::make_index_sequence<N>{}));

template <typename T, std::size_t N>
using tuple_fixed_type = decltype(get_fixed_tuple<T, N>());

以下是完整的工作示例

#include <tuple>
#include <utility>

template <typename T, std::size_t ... Is>
constexpr auto gft_helper (std::index_sequence<Is...> const &)
   -> decltype(std::make_tuple( ((void)Is, std::declval<T>())... ));

template <typename T, std::size_t N>
constexpr auto get_fixed_tuple ()
  -> decltype(gft_helper<T>(std::make_index_sequence<N>{}));

template <typename T, std::size_t N>
using tuple_fixed_type = decltype(get_fixed_tuple<T, N>());

int main()
 {
   auto ft = tuple_fixed_type<long, 3u>{};

   static_assert( std::is_same<decltype(ft), std::tuple<long, long, long>>{} );
 }