Why isn't a for-loop a compile-time expression?

后端 未结 4 1909
自闭症患者
自闭症患者 2020-11-30 09:32

If I want to do something like iterate over a tuple, I have to resort to crazy template metaprogramming and template helper specializations. For example, the following progr

4条回答
  •  无人及你
    2020-11-30 10:31

    Here's a way to do it that does not need too much boilerplate, inspired from http://stackoverflow.com/a/26902803/1495627 :

    template
    struct num { static const constexpr auto value = N; };
    
    template 
    void for_(F func, std::index_sequence)
    {
      using expander = int[];
      (void)expander{0, ((void)func(num{}), 0)...};
    }
    
    template 
    void for_(F func)
    {
      for_(func, std::make_index_sequence());
    }
    

    Then you can do :

    for_([&] (auto i) {      
      std::get(t); // do stuff
    });
    

    If you have a C++17 compiler accessible, it can be simplified to

    template 
    void for_(F func, std::index_sequence)
    {
      (func(num{}), ...);
    }
    

提交回复
热议问题