details of std::make_index_sequence and std::index_sequence

后端 未结 2 411
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 04:47

I\'m enjoying ramping up on variadic templates and have started fiddling about with this new feature. I\'m trying to get my head around the implementation details of s

2条回答
  •  迷失自我
    2020-11-30 05:37

    For the sake of completeness, I'll add a more modern implementation of std::make_index_sequence, using if constexpr and auto, that make template programming a lot more like "normal" programming.

    template 
    struct index_sequence {};
    
    template 
    auto make_index_sequence_impl() {
        // only one branch is considered. The other may be ill-formed
        if constexpr (N == 0) return index_sequence(); // end case
        else return make_index_sequence_impl(); // recursion
    }
    
    template 
    using make_index_sequence = std::decay_t())>;
    

    I strongly advise to use this style of template programming, which is easier to reason about.

提交回复
热议问题