c – 如何创建包含n次相同类型的类型列表(对于可变对象模板)?

我想要我的班级
template <class T,unsigned int n>
class X;

创建一个包含n倍类型T的std ::元组.有没有一个特别整齐的方式呢?有没有一个很好的方法来做这个任意可变的模板类?

这是我先做的

#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,std::tuple<Args...>>
{
    typedef std::tuple<Args...> type;
};

template <class T,unsigned int n>
struct simple_repeat
{
    using type = typename simple_repeat_helper<T,std::tuple<>>::type;
};

但实际上,我不需要这个std :: tuple,而是另一个类似的类.所以我以为我会创建一个更通用的版本:

template <class,template <class...> class,class>
struct repeat_helper;

template <class T,template <class...> class M,class... Args>
struct repeat_helper<T,M,M<Args...>>
{
    typedef M<Args...> type;
};

template <class T,M<Args...>>
{
    typedef typename repeat_helper<T,M<Args...,template <class...> class M = std::tuple>
struct repeat
{
    using type = typename repeat_helper<T,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> >’

任何关于这个错误的帮助将不胜感激!

解决方法

我会这样做:
template<typename,typename>
struct append_to_type_seq { };

template<typename T,typename... Ts,template<typename...> class TT>
struct append_to_type_seq<T,TT<Ts...>>
{
    using type = TT<Ts...,T>;
};

template<typename T,unsigned int N,template<typename...> class TT>
struct repeat
{
    using type = typename
        append_to_type_seq<
            T,typename repeat<T,N-1,TT>::type
            >::type;
};

template<typename T,template<typename...> class TT>
struct repeat<T,TT>
{
    using type = TT<>;
};

作为一个小考验:

#include <type_traits>
#include <tuple>

template<typename... Ts>
struct X { };

int main()
{
    repeat<double,std::tuple>::type t = std::make_tuple(1.,5.);
    static_assert(
        std::is_same<
            decltype(t),double>
        >::value,"!");

    repeat<double,3,X>::type y;
    static_assert(
        std::is_same<decltype(y),X<double,double>>::value,"!");
}

最后一个live example.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...