如何在C++中循环遍历多个函数

How to loop through multiple functions in C++?

本文关键字:遍历 函数 循环 C++      更新时间:2023-10-16

我似乎找不到有关以下此类事情的任何相关信息。

假设您有一个包含多种方法的程序(例如,一组自定义测试)。

您如何根据以下伪代码循环访问它们

for(int i= 0;  i < 10 ; i ++)
    {
        function(i)();
    }

这样它将通过这个循环,从而启动方法函数0、函数 1、函数 2、函数 3、函数 4、函数 5、函数 6、函数 7、函数 8、函数 9。

如果有办法在 C# 或 Java 中也能做到这一点,那么他们的信息也将不胜感激。

在C++中,我能想到的唯一方法是使用函数指针数组。看这里。对于支持反射的Java,请参阅此处。对于同样支持反射的 C#,这个。

您需要的语言

功能称为"反射",这是C++没有的功能。您需要显式命名要调用的函数。

好吧,如果你有一个函数指针数组,你可以做这样的事情:

void (*myStuff[256])(void);

然后,当您想要调用每个函数时,只需在迭代时取消引用每个函数即可。

请记住,数组中的每个函数都必须具有相同的参数签名和返回类型。

这是一个使用 Boost.Function 和 Boost.Bind 的解决方案,其中循环不需要担心你正在调用的函数的参数签名(我没有在编译器中测试过它,但我在一个我知道有效的项目中有非常相似的代码):

#include <vector>
#include <boost/function.hpp>
#include <boost/bind.hpp>
using std::vector;
using boost::function;
using boost::bind;
void foo (int a);
void bar (double a);
void baz (int a, double b);
int main()
{
   // Transform the functions so that they all have the same signature,
   // (with pre-determined arguments), and add them to a vector:
   vector<function<void()>> myFunctions;
   myFunctions.push_back(bind(&foo, 1));
   myFunctions.push_back(bind(&bar, 2.0));
   myFunctions.push_back(bind(&baz, 1, 2.0));
   // Call the functions in a loop:
   vector<function<void()>>::iterator it = myFunctions.begin();
   while (it != myFunctions.end())
   {
       (*it)();
      it++;
   }
   return 0;
}

请注意,如果您的编译器支持 C++11,则可以更轻松地执行循环:

   // Call the functions in a loop:
   for (const auto& f : myFunctions)
   {
      f();
   }

Boost.Bind 还支持动态传入某些参数,而不是将它们绑定到预定值。有关更多详细信息,请参阅文档。您还可以简单地更改上述代码以支持返回值(如果它们属于同一类型),方法是将void替换为返回类型,并更改循环以对返回值执行某些操作。