C++中函数名的生成和调用

Function name generation and calling in C++

我有 10 个具有通用名称的函数,return 引用如下:

int& function0();
int& function1();
...int& functionN();

如您所见,函数名称中只有一个字母发生了变化。每个功能做不同的工作。我的用例有一定的长度,比如 L,我必须调用从 0 到 L 的函数。所以我想以某种方式生成这些函数名称并调用它们,而不是对基于 L 的所有函数调用进行硬编码。所以如果在一个循环中索引 i 从 0 到 L,对于每个 i 我想调用 functioni()。

我尝试过的一种方法是将这些函数存储到函数指针数组中,但这不起作用,因为这些函数 return 引用和引用数组是不可能的。我还尝试使用宏连接来生成函数名,但这也是不可能的,因为宏不能在预处理时替换某些变量的值(MACRO(function,i) 不替换 i 的值,连接到 functioni)。

我如何在 C++ 中做这样的事情?

这在 C++ 中是不可能的,但在您的情况下,函数指针数组似乎是一个很好的解决方案:

typedef int& (* functionPtr)();
functionPtr functions[N];
// or without typedef: int& (* functions[N])();
functions[0] = foo; // assign a function named foo to index 0
int& i = functions[0](); // call function at index 0

您可以存储一个函数指针数组,如

C++11, you could have an array of function closures, e.g. use std::function and lambda expressions。您可以有一些 std::map<std:string,std::function<int&(void)>> 将名称与闭包相关联。

您可以将调用包装在某些函数中,例如

int& dofunction(int n) {
 switch 0: return function0();
 switch 1: return function1();
 /// etc...
};

您可以编写一些小脚本(例如在 awk 中,python、shell 等....)来生成上述 dofunction 的 C++ 代码。

最后,在某些操作系统上(例如 Linux 和大多数 POSIX),您可以使用 dlopen(3) (with a NULL filename) then dlsym. You would then declare extern "C" int& function0(); (to avoid name mangling -otherwise you need to pass the mangled name to dlsym) and you need to link the program with -rdynamic -ldl; see C++ dlopen mini howto.[=21= 在运行时通过名称检索函数指针。 ]