C++11: Compile-time Array with Logarithmic Evaluation Depth

后端 未结 3 475
终归单人心
终归单人心 2020-11-29 03:29

One way to implement a C++11 array that has its elements initialized by a function of their index calculated by the compiler and have the results stored in the data section

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 04:26

    If what you're using in the code is a weird form of the indices trick, here's an implementation that has O(log N) instantiations:

    // using aliases for cleaner syntax
    template using Invoke = typename T::type;
    
    template struct seq{ using type = seq; };
    
    template struct concat;
    
    template
    struct concat, seq>
      : seq{};
    
    template
    using Concat = Invoke>;
    
    template struct gen_seq;
    template using GenSeq = Invoke>;
    
    template
    struct gen_seq : Concat, GenSeq>{};
    
    template<> struct gen_seq<0> : seq<>{};
    template<> struct gen_seq<1> : seq<0>{};
    
    // example
    
    template
    void f(seq);
    
    int main(){
      f(gen_seq<6>());
    }
    

    Live example.

提交回复
热议问题