首页 > 解决方案 > c ++通用编译时for循环

问题描述

for在某些情况下,在编译时评估/展开循环可能很有用/必要。例如,要遍历 a 的元素tuple,需要使用std::get<I>,这取决于模板int参数I,因此必须在编译时对其进行评估。使用编译递归可以解决一个特定的问题,例如这里讨论这里,特别是std::tuple 这里

但是,我对如何实现通用编译时for循环很感兴趣。

下面的c++17代码实现了这个想法

#include <utility>
#include <tuple>
#include <string>
#include <iostream>

template <int start, int end, template <int> class OperatorType, typename... Args>
void compile_time_for(Args... args)
{
  if constexpr (start < end)
         {
           OperatorType<start>()(std::forward<Args>(args)...);
           compile_time_for<start + 1, end, OperatorType>(std::forward<Args>(args)...);
         }    
}

template <int I>
struct print_tuple_i {
  template <typename... U>
  void operator()(const std::tuple<U...>& x) { std::cout << std::get<I>(x) << " "; }
};

int main()
{
  std::tuple<int, int, std::string> x{1, 2, "hello"};

  compile_time_for<0, 3, print_tuple_i>(x);

  return 0;
}

虽然代码可以工作,但能够简单地为例程提供一个模板函数compile_time_for,而不是在每次迭代时实例化一个模板类会更好。

然而,像下面这样的代码不能编译c++17

#include <utility>
#include <tuple>
#include <string>
#include <iostream>

template <int start, int end, template <int, typename...> class F, typename... Args>
void compile_time_for(F f, Args... args)
{
  if constexpr (start < end)
         {
           f<start>(std::forward<Args>(args)...);
           compile_time_for<start + 1, end>(f, std::forward<Args>(args)...);
         }    
}

template <int I, typename... U>
void myprint(const std::tuple<U...>& x) { std::cout << std::get<I>(x) << " "; }

int main()
{
  std::tuple<int, int, std::string> x{1, 2, "hello"};

  compile_time_for<0, 3>(myprint, x);

  return 0;
}

使用 gcc 7.3.0 和选项std=c++17,第一个错误是

for2.cpp:7:25: error: ‘auto’ parameter not permitted in this context
 void compile_time_for(F f, Args... args)

问题是:

  1. 有没有办法compile_time_for让它接受一个模板函数作为它的第一个参数?
  2. 如果问题 1. 是肯定的,那么在第一个工作代码中是否存在开销,因为例程OperatorType<start>在每次循环迭代时都会创建一个类型的对象?
  3. 是否有计划在即将到来的时候引入类似编译时 for 循环的功能c++20

标签: c++c++17variadic-templatestemplate-meta-programmingc++20

解决方案


  1. 有没有办法编写 compile_time_for 使其接受模板函数作为其第一个参数?

简短的回答:没有。

长答案:模板函数不是对象,是对象的集合,您可以将其作为参数、对象而不是对象集合传递给函数。

此类问题的通常解决方案是将模板函数包装在一个类中并传递该类的一个对象(或简单的类型,如果该函数被包装为静态方法)。这正是您在工作代码中采用的解决方案。

  1. 如果问题 1. 是肯定的,那么在第一个工作代码中是否存在开销,因为例程在每次循环迭代时都会创建一个 OperatorType 类型的对象?

问题 1 是否定的。

  1. 是否有计划在即将到来的 c++20 中引入诸如编译时 for 循环之类的功能?

我对 C++20 的了解不足以回答这个问题,但我想没有传递一组函数。

std::make_index_sequence无论如何,您可以使用/std::index_sequence从 C++14 开始执行一种循环编译时间。

例如,如果您接受在myprint()函数外部提取 touple 值,则可以将其包装在 lambda 中并编写如下内容(也使用 C++17 模板折叠;在 C++14 中稍微复杂一些)

#include <utility>
#include <tuple>
#include <string>
#include <iostream>

template <typename T>
void myprint (T const & t)
 { std::cout << t << " "; }

template <std::size_t start, std::size_t ... Is, typename F, typename ... Ts>
void ctf_helper (std::index_sequence<Is...>, F f, std::tuple<Ts...> const & t)
 { (f(std::get<start + Is>(t)), ...); }

template <std::size_t start, std::size_t end, typename F, typename ... Ts>
void compile_time_for (F f, std::tuple<Ts...> const & t)
 { ctf_helper<start>(std::make_index_sequence<end-start>{}, f, t); }

int main()
{
  std::tuple<int, int, std::string> x{1, 2, "hello"};

  compile_time_for<0, 3>([](auto const & v){ myprint(v); }, x);

  return 0;
}

如果您真的想提取函数内的元组元素(或元组元素),我能想象的最好的方法是将您的第一个示例转换如下

#include <utility>
#include <tuple>
#include <string>
#include <iostream>

template <std::size_t start, template <std::size_t> class OT,
          std::size_t ... Is, typename... Args>
void ctf_helper (std::index_sequence<Is...> const &, Args && ... args)
 { (OT<start+Is>{}(std::forward<Args>(args)...), ...); }

template <std::size_t start, std::size_t end,
          template <std::size_t> class OT, typename... Args>
void compile_time_for (Args && ... args)
 { ctf_helper<start, OT>(std::make_index_sequence<end-start>{},
                         std::forward<Args>(args)...); }

template <std::size_t I>
struct print_tuple_i
 {
   template <typename ... U>
   void operator() (std::tuple<U...> const & x)
    { std::cout << std::get<I>(x) << " "; }
 };

int main()
{
  std::tuple<int, int, std::string> x{1, 2, "hello"};

  compile_time_for<0u, 3u, print_tuple_i>(x);

  return 0;
}

- 编辑 -

OP问

与我的第一个代码相比,使用 index_sequence 有什么优势吗?

我不是专家,但这样可以避免递归。从模板的角度来看,编译器具有严格的递归限制。这样你就可以避免它们。

此外,如果您设置模板参数,您的代码也不会编译end > start。(可以想象一种情况,您希望编译器确定一个循环是否被实例化)

我想您的意思是我的代码无法编译 if start > end

不好的部分是没有检查这个问题,所以在这种情况下编译器也会尝试编译我的代码;所以遇到

 std::make_index_sequence<end-start>{}

whereend - start是一个负数,但由需要无符号数的模板使用。所以end - start成为一个非常大的正数,这可能会导致问题。

你可以避免这个问题强加一个static_assert()内部compile_time_for()

template <std::size_t start, std::size_t end,
          template <std::size_t> class OT, typename... Args>
void compile_time_for (Args && ... args)
 { 
   static_assert( end >= start, "start is bigger than end");

   ctf_helper<start, OT>(std::make_index_sequence<end-start>{},
                         std::forward<Args>(args)...);
 }

或者您可以使用 SFINAE 禁用该功能

template <std::size_t start, std::size_t end,
          template <std::size_t> class OT, typename... Args>
std::enable_if_t<(start <= end)> compile_time_for (Args && ... args)
 { ctf_helper<start, OT>(std::make_index_sequence<end-start>{},
                         std::forward<Args>(args)...); }

如果需要,可以使用 SFINAE 添加重载compile_time_for()版本来管理end < start案例

template <std::size_t start, std::size_t end,
          template <std::size_t> class OT, typename ... Args>
std::enable_if_t<(start > end)> compile_time_for (Args && ...)
 { /* manage the end < start case in some way */ }

推荐阅读