Reuse nested loops without copy and paste

流过昼夜 提交于 2019-11-30 14:05:37

Use templates:

template<typename Func>
inline void do_something_loop(Func f)
{
    for (int a=1; a<MAX_A; ++a) 
      for (int b=1; b<MAX_B; ++b) 
        for (int c=1; c<MAX_C; ++c) 
        { 
           f(a, b ,c); 
        } 
}

This can be called with any function pointer or function object that matches the signature, e.g.:

void do_something(int a, int b, int c) { /* stuff */ }

do_something_loop(do_something);

Or with a function object:

struct do_something
{
    void operator()(int a, int b, int c) { /* stuff */ }
};

do_something_loop(do_something()); 

Or if your compiler supports C++11, even with a lambda:

do_something_loop([](int a, int b, int c) { /* stuff */ });

Note that you could also declare the f parameter as a function pointer with the signature void(*f)(int,int,int) instead of using a template, but that's less flexible (it won't work on function objects (including the result of std::bind) or lambdas).

Make a helper loop function:

template<typename Work>
void loop(Work work) {
  for (int a=1; a<MAX_A; ++a)
    for (int b=1; b<MAX_B; ++b)
      for (int c=1; c<MAX_C; ++c)
      {
        work(a, b ,c);
      }
}

Define the work to be done:

void some_work(int a, int b, int c) {
}

Then use:

loop(some_work);

Note that now you don't need to use only function, but you can use a function object (object for which an operator() is overloaded).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!