Implementation C++14 make_integer_sequence

前端 未结 7 692
-上瘾入骨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

    I found very fast and needless deep recursion version of implementation of make_index_sequence. In my PC it compiles with N = 1 048 576 , with 2 s. (PC : Centos 6.4 x86, i5, 8 Gb RAM, gcc-4.4.7 -std=c++0x -O2 -Wall).

    #include  // for std::size_t
    
    template< std::size_t ... i >
    struct index_sequence
    {
        typedef std::size_t value_type;
    
        typedef index_sequence type;
    
        // gcc-4.4.7 doesn't support `constexpr` and `noexcept`.
        static /*constexpr*/ std::size_t size() /*noexcept*/
        { 
            return sizeof ... (i); 
        }
    };
    
    
    // this structure doubles index_sequence elements.
    // s- is number of template arguments in IS.
    template< std::size_t s, typename IS >
    struct doubled_index_sequence;
    
    template< std::size_t s, std::size_t ... i >
    struct doubled_index_sequence< s, index_sequence >
    {
        typedef index_sequence type;
    };
    
    // this structure incremented by one index_sequence, iff NEED-is true, 
    // otherwise returns IS
    template< bool NEED, typename IS >
    struct inc_index_sequence;
    
    template< typename IS >
    struct inc_index_sequence{ typedef IS type; };
    
    template< std::size_t ... i >
    struct inc_index_sequence< true, index_sequence >
    {
        typedef index_sequence type;
    };
    
    
    
    // helper structure for make_index_sequence.
    template< std::size_t N >
    struct make_index_sequence_impl : 
               inc_index_sequence< (N % 2 != 0), 
                    typename doubled_index_sequence< N / 2,
                               typename make_index_sequence_impl< N / 2> ::type
                   >::type
           >
    {};
    
     // helper structure needs specialization only with 0 element.
    template<>struct make_index_sequence_impl<0>{ typedef index_sequence<> type; };
    
    
    
    // OUR make_index_sequence,  gcc-4.4.7 doesn't support `using`, 
    // so we use struct instead of it.
    template< std::size_t N >
    struct make_index_sequence : make_index_sequence_impl::type {};
    
    //index_sequence_for  any variadic templates
    template< typename ... T >
    struct index_sequence_for : make_index_sequence< sizeof...(T) >{};
    
    
    // test
    typedef make_index_sequence< 1024 * 1024 >::type a_big_index_sequence;
    int main(){}
    

提交回复
热议问题