在C ++ 11中打印编译时整数序列

ozm*_*zma 0 c++ variadic sequence variadic-templates c++11

因此,我正在做一些作业,其中我必须在C ++ 11中编写自己的编译时整数序列,并为其编写一些函数(print,concat,sort等),但是我有点缠着我的头如何写这些东西的麻烦。

template<typename T, typename Comp = std::less<int>>
struct Facility{

    template<T ... Nums>
    struct List{

        struct Element<T ... nums>{};

        template<unsigned num, T val, T ... rest>
        struct Element{
            unsigned index = num;
            T value = val;
            Element<index-1, rest...> others;
        };

        template<unsigned num, T val, T ... rest>
        struct Element<0, val>{
            unsigned index = 0;
            T value = val;
        };

        static constexpr Element<sizeof...(Nums)-1,Nums...> elem = {};

        static void Print()
        {
            // Prints out the list
        }
    };

};

using IntList = typename Facility<int>::List<intlist...>;

int main()
{
    using List1 = IntList<1, 2, 3>;
    List1::print()
}
Run Code Online (Sandbox Code Playgroud)

我只是想知道自己是否走在正确的道路上,所以我不会陷入僵局。我不确定100%的static print()和中的static constexpr成员List,尽管我想不出任何其他方法来使其正常工作。

Yak*_*ont 5

不必像这样嵌套类型。写一个<T,Ts...>序列。

不要将操作与类型耦合。从外部写入操作(尾部,头部)。

std::integer_sequence<T,T...>C ++ 14 获得灵感。

如果需要在OP中使用该接口,请改用扁平接口编写。

到目前为止,最容易编写的排序是合并排序。

Exploit std::integral_constant,这是C ++ 11。编写一个使用模板模板参数和一个整数列表的元函数,并将每个整数常量作为类型传递给,并生成一个类型列表template<class...Ts>struct types{};作为输出。叫这个foreach_int

编写foreach_type,它接受一个类型列表并在每个元素上调用一个函数对象。现在打印很简单;template<class list> void print_list(){ foreach_type( foreach_int< idenitity, list >{}, print{} ); }哪里template<cls T> void print(T && t}{std::cout<<t;}

这些中的每一个都更容易推论,组成它们会使您“分别打印”。

但也许我有点疯了。