Implementation C++14 make_integer_sequence

前端 未结 7 678
-上瘾入骨i
-上瘾入骨i 2020-11-22 03:28

I tried to implement the C++14 alias template make_integer_sequence, which simplifies the creation of the class template integer_sequence.

templ         


        
7条回答
  •  不知归路
    2020-11-22 03:58

    Here is another slightly more general variation of Xeo's logarithmic answer which provides make_integer_sequence for arbitrary types. This is done by using std::integral_constant in order to avoid the dreaded "template argument involves template parameter" error.

    template
    struct integer_sequence
    {
        using value_type = Int;
        static constexpr std::size_t size() noexcept
        {
            return sizeof...(Ints);
        }
    };
    
    template
    using index_sequence = integer_sequence;
    
    namespace
    {
        // Merge two integer sequences, adding an offset to the right-hand side.
        template
        struct merge;
    
        template
        struct merge<
            std::integral_constant,
            integer_sequence,
            integer_sequence
        >
        {
            using type = integer_sequence;
        };
    
        template
        struct log_make_sequence
        {
            using L = std::integral_constant;
            using R = std::integral_constant;
            using type = typename merge<
                L,
                typename log_make_sequence::type,
                typename log_make_sequence::type
            >::type;
        };
    
        // An empty sequence.
        template
        struct log_make_sequence>
        {
            using type = integer_sequence;
        };
    
        // A single-element sequence.
        template
        struct log_make_sequence>
        {
            using type = integer_sequence;
        };
    }
    
    template
    using make_integer_sequence =
        typename log_make_sequence<
            Int, std::integral_constant
        >::type;
    
    template
    using make_index_sequence = make_integer_sequence;
    

    Demo: coliru

提交回复
热议问题