c++ generic compile-time for loop

前端 未结 2 1515
长发绾君心
长发绾君心 2021-01-07 23:29

In some contexts, it could be useful/necessary to have a for loop evaluated/unrolled at compile time. For example, to iterate over the elements of a tuple

2条回答
  •  离开以前
    2021-01-08 00:29

    I'll answer on the question how to fix your last code sample.

    The reason why it doesn't compile is here:

    template  class F, typename... Args>
    void compile_time_for(F f, Args... args)
                          /\
    

    F is a template, you can't have an object of a template class without template parameters being substituted. E.g. you can't have on object of std::vector type, but can have object of std::vector. I suggest you to make F functor with a template operator() :

    #include 
    #include 
    #include 
    #include 
    
    template 
    void compile_time_for(F f, Args... args)
    {
      if constexpr (start < end)
             {
               f.template operator()(std::forward(args)...);
               compile_time_for(f, std::forward(args)...);
             }    
    }
    
    struct myprint
    {
        template 
        void operator()(const std::tuple& x) { std::cout << std::get(x) << " "; }
    };
    
    int main()
    {
      std::tuple x{1, 2, "hello"};
    
      compile_time_for<0, 3>(myprint(), x);
    
      return 0;
    }
    

提交回复
热议问题