如何将函数设置为变量并从中调用?

How to set a function into a variable and call from it?

本文关键字:调用 变量 函数 设置      更新时间:2023-10-16

我想知道是否可以在C++中做到这一点?

例如:

varFunction = void TestFunction();
RunCode(varFunction);

对于 C++11 及更高版本,您可以使用std::function来存储函数指针和函数对象。

但是存储函数指针从一开始就可以在C++中使用。这意味着您可以存储函数的地址并在以后调用它。

顺便说一句,lambda 表达式也非常有用(它们表示的闭包可以作为std::function-s 赋值或传递(


以下示例显示了实现您要求的三种不同方法:

#include <iostream>
#include <functional>
void RunCode(const std::function<void()>& callable) {
callable();
}
void TestFunction() {
std::cout << "TestFunction is called..." << std::endl;
}
int main() {
std::function<void()> varFunction_1 = TestFunction;
void (*varFunction_2)() = TestFunction;
RunCode(varFunction_1);
RunCode(varFunction_2);
RunCode([]() { std::cout << "TestLambda is called..." << std::endl; });
return 0;
}

但这只是冰山一角,将函数指针和函数对象作为参数传递在算法库中非常常见。

C++提供了几种方法来实现它。

例如,您可以使用std::function模板:包含<functional>并使用以下语法(演示(:

std::function<void()> varFunction(TestFunction);
varFunction();

您还可以使用函数指针(关于该主题的问答(。

为了完整起见,您可以声明 C 样式的函数类型,如下所示:

typedef int (*inttoint)(int);

这将创建一个类型inttoint,该类型可以存储任何将 int 作为参数并返回 int 的函数。您可以按如下方式使用它。

// Define a function
int square(int x) { return x*x; }
// Save the function in sq variable
inttoint sq { square };
// Execute the function
sq(4);

从 C++11 开始,这些变量也可以存储 lambda 函数,如下所示

inttoint half { [](int x) { return x/2; } };

并同上使用它。

最简单的方法是使用如下所示的 lambda 表达式:

auto add = [](int a, int b) { return a+b; };
cout << add(10, 20) << endl; // Output: 30

有关 lambda 表达式工作原理的更多信息:http://en.cppreference.com/w/cpp/language/lambda