循环遍历C++中函数的所有参数

mem*_*emC 4 c++

我想对函数的一堆参数进行相同的处理.有没有办法循环所有参数?我按照以下代码中的方式进行操作,但是想看看是否有一种紧凑的方法来执行此操作.

 void methodA(int a1, int a2, int b1, double b2){   
        //.. some code 
        methodB(a1, f(a1));
        methodB(a2, f(a2));
        methodB(b1, f(b1));
        methodB(b2, f(b2));
        // more code follows ...

   }

int f(int a){
      // some function. 
   return a*10;
}

double  f(double b){
   return b/2.0;
}
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 6

您可以使用可变参数模板:

template <typename T, typename ...Args>
void methodAHelper(T && t, Args &&... args)
{
  methodB(t, f(t));
  methodAHelper(std::forward<Args>(args)...);
}

void methodAHelper() { }

template <typename ...Args>
void methodA(Args &&... args)
{
  // some code
  methodAHelper(std::forward<Args>(args)...);
  // some other code
}
Run Code Online (Sandbox Code Playgroud)

&&如果你知道你的methodB调用不知道rvalue引用,你可以摆脱转发和转发,这将使代码更简单(你可以const Args &...改为),例如:

methodAHelper(const T & t, const Args &... args)
{
  methodB(t, f(t));
  methodAHelper(args...);
}
Run Code Online (Sandbox Code Playgroud)

你也可以考虑改变methodB:由于第二个参数是第一个参数的函数,你可能只能够通过第一个参数,进行调用f() 内部methodB().这减少了耦合和相互依赖; 例如,整个声明f只需要知道实现methodB.但这取决于你的实际情况.

另外,如果只有一个的过载methodB,其第一个参数是类型的T,那么你可以只通过一个std::vector<T>methodA,并遍历它:

void methodA(const std::vector<T> & v)
{
  // some code
  for (auto it = v.cbegin(), end = v.cend(); it != end; ++it)
    methodB(*it, f(*it));
  // some more code
}

int main() { methodA(std::vector<int>{1,2,3,4}); }
Run Code Online (Sandbox Code Playgroud)