我想要我的课
template <class T, unsigned int n>
class X;
创建一个std::tuple
包含n
时间类型的T
。有没有特别巧妙的方法?对于任意可变参数模板类,还有一种很好的方法吗?
这是我首先做的:
#include <tuple>
template <class, unsigned int, class>
struct simple_repeat_helper;
template <class T, unsigned int n, class... Args>
struct simple_repeat_helper<T, n, std::tuple<Args...>>
{
typedef typename simple_repeat_helper<T, n-1, std::tuple<Args..., T>>::type type;
};
template <class T, class... Args>
struct simple_repeat_helper<T, 0, std::tuple<Args...>>
{
typedef std::tuple<Args...> type;
};
template <class T, unsigned int n>
struct simple_repeat
{
using type = typename simple_repeat_helper<T, n, std::tuple<>>::type;
};
但实际上,我不需要这个std::tuple
,而是另一个类似的类。所以我想我会创建一个更通用的版本:
template <class, unsigned int, template <class...> class, class>
struct repeat_helper;
template <class T, template <class...> class M, class... Args>
struct repeat_helper<T, 0, M, M<Args...>>
{
typedef M<Args...> type;
};
template <class T, unsigned int n, template <class...> class M, class... Args>
struct repeat_helper<T, n, M, M<Args...>>
{
typedef typename repeat_helper<T, n-1, M, M<Args..., T>>::type type;
};
template <class T, unsigned int n, template <class...> class M = std::tuple>
struct repeat
{
using type = typename repeat_helper<T, n, M, M<>>::type;
};
我以为我可以这样使用它:
repeat<double, 5, std::tuple>::type x = std::make_tuple( 1., 2., 3., 4., 5. );
但不幸的是,由于以下原因无法编译:
ambiguous class template instantiation for ‘struct repeat_helper<double, 0u, std::tuple, std::tuple<double, double, double, double, double> >’
对此错误的任何帮助将不胜感激!