C++ 如何在C+中创建一个在编译时大小已知的固定类型元组+;17?
我想创建一个通用元素类型的元组类型,其长度在编译时已知。例如,如果我有C++ 如何在C+中创建一个在编译时大小已知的固定类型元组+;17?,c++,c++17,variadic-templates,template-meta-programming,stdtuple,C++,C++17,Variadic Templates,Template Meta Programming,Stdtuple,我想创建一个通用元素类型的元组类型,其长度在编译时已知。例如,如果我有 static constexpr const std::size_t compiletime_size = 2; using tuple_int_size_2 = magic (int, compiletime_size); tuple\u int\u size\u 2的类型应与std::tuple的类型相同,这可以通过递归实现: #include <tuple> template <size_t N
static constexpr const std::size_t compiletime_size = 2;
using tuple_int_size_2 = magic (int, compiletime_size);
tuple\u int\u size\u 2
的类型应与std::tuple
的类型相同,这可以通过递归实现:
#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;
}
#包括
模板
结构魔法{
使用tuple\u type=typename magic::tuple\u type;
};
模板
结构魔法{
使用tuple_type=std::tuple;
};
int main()
{
auto t=typename magic::tuple_type{};
返回0;
}
不过,我想知道,对于您试图解决的任何任务,
std::array
是否会是一个更简单、更直接的解决方案。没有递归,有两个声明的(未定义的)帮助函数和一个使用的
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>());
模板
constexpr自动gft\u助手(std::index\u序列const&)
->decltype(std::make_tuple(((void)是,std::declval())…);
模板
constexpr自动获取固定的元组()
->decltype(gft_helper(std::make_index_sequence{}));
模板
使用tuple_fixed_type=decltype(get_fixed_tuple());
下面是一个完整的工作示例
#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>>{} );
}
#包括
#包括
模板
constexpr自动gft\u助手(std::index\u序列const&)
->decltype(std::make_tuple(((void)是,std::declval())…);
模板
constexpr自动获取固定的元组()
->decltype(gft_helper(std::make_index_sequence{}));
模板
使用tuple_fixed_type=decltype(get_fixed_tuple());
int main()
{
auto ft=元组\固定\类型{};
静态_断言(std::is_same{});
}
怎么办?我希望将其扩展到魔法的情况(int,int\u size,double,double\u size,…);所以我不能使用std::array