Implementation C++14 make_integer_sequence

前端 未结 7 675
-上瘾入骨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 04:06

    This is basically me hacking around Xeo's solution: Making community wiki - if appreciative, please upvote Xeo.

    ...just modified until I felt it couldn't get any simpler, renamed and added value_type and size() per the Standard (but only doing index_sequence not integer_sequence), and code working with GCC 5.2 -std=c++14 could run otherwise unaltered under older/other compilers I'm stuck with. Might save someone some time / confusion.

    // based on http://stackoverflow.com/a/17426611/410767 by Xeo
    namespace std  // WARNING: at own risk, otherwise use own namespace
    {
        template 
        struct index_sequence
        {
            using type = index_sequence;
            using value_type = size_t;
            static constexpr std::size_t size() noexcept { return sizeof...(Ints); }
        };
    
        // --------------------------------------------------------------
    
        template 
        struct _merge_and_renumber;
    
        template 
        struct _merge_and_renumber, index_sequence>
          : index_sequence
        { };
    
        // --------------------------------------------------------------
    
        template 
        struct make_index_sequence
          : _merge_and_renumber::type,
                                typename make_index_sequence::type>
        { };
    
        template<> struct make_index_sequence<0> : index_sequence<> { };
        template<> struct make_index_sequence<1> : index_sequence<0> { };
    }
    

    Notes:

    • the "magic" of Xeo's solution is in the declaration of _merge_and_renumber (concat in his code) with exactly two parameters, while the specilisation effectively exposes their individual parameter packs

    • the typename...::type in...

      struct make_index_sequence
        : _merge_and_renumber::type,
                              typename make_index_sequence::type>
      

        avoids the error:

    invalid use of incomplete type 'struct std::_merge_and_renumber, std::index_sequence<0ul> >'
    

提交回复
热议问题