通过模板参数给定其长度,在编译时生成相同类型的std :: tuple [英] Produce std::tuple of same type in compile time given its length by a template argument
本文介绍了通过模板参数给定其长度,在编译时生成相同类型的std :: tuple的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在c ++中,我如何实现带有int模板参数(指示元组长度)的函数并生成具有该长度的std :: tuple?
In c++, how can I implement a function with an int template argument indicating the tuple length and produce a std::tuple with that length?
例如
func<2>() returns std::tuple<int, int>();
func<5>() returns std::tuple<int, int, int, int, int>().
推荐答案
这是带有别名模板的递归解决方案,可在C ++ 11中实现:
Here is a recursive solution with alias template and it's implementable in C++11:
template <size_t I,typename T>
struct tuple_n{
template< typename...Args> using type = typename tuple_n<I-1, T>::template type<T, Args...>;
};
template <typename T>
struct tuple_n<0, T> {
template<typename...Args> using type = std::tuple<Args...>;
};
template <size_t I,typename T> using tuple_of = typename tuple_n<I,T>::template type<>;
例如,如果我们想要"tuple of 3 doubles"
,我们可以写:
For example if we want "tuple of 3 doubles"
we can write:
tuple_of<3, double> t;
这篇关于通过模板参数给定其长度,在编译时生成相同类型的std :: tuple的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文