如何将函数设置为变量并从中调用?
How to set a function into a variable and call from it?
我想知道是否可以在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
相关文章:
- 变量没有改变?通过向量的函数调用
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 从类型std::函数传递变量失败,尽管调用方期望的类型完全相同
- 尝试调用 .h 文件中定义的变量时出现变量未定义错误
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- C++类型特征,以查看是否可以<uint32_t>对类型"K"的任何变量调用"static_cast(k)"
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 使用静态变量的递归调用的不同输出
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 在另一个函数 (c++) 中调用变量
- 修改程序的入口点时未调用全局变量的构造函数
- C++变量在调用 x64 程序集函数后重置为 0
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 为变量模板的每个参数调用模板函数
- 函数参数的名称与调用函数时使用的变量相同是否有效?
- 如何使用Stroustrup的Fltk Text类调用变量?
- 从结构实例调用变量语法问题C++
- C++模板:一个按名称调用变量的模板
- C++自定义用户输入调用变量
- 如何在c++中从嵌套类中调用变量