我可以在构造函数参数中定义一个要在函数指针中使用的函数吗
Can i define a function to be used in a function pointer, in a constructor argument
我正在尝试创建一个按钮类型的系统,它有四个功能(激活、停用、选择、取消选择),我将这四个功能作为函数指针。
我想知道是否有可能在构造函数中使用这些参数,然后能够在构造函数中动态定义函数。
类似于:
Button({(if a == 1) a++},{(if a == 2) a--})
等等。
如果可能的话,我真的不知道该怎么称呼,所以很难准确地搜索我想要的东西。
感谢
它被称为lambda表达式。在C++11中,您可以使用以下内容:
Button([](int&a){if (a == 1) a++;},[](int&a){if (a == 2) a--;})
在C++11中,您可以使用lambda表达式。
例如,如果要将它们存储在其他成员函数中以供以后调用,您甚至可以将它们作为std::function
参数。
以这种方式声明您的构造函数:
Button(std::function<void(int&)> func1, std::function<void(int&)> func2);
并在创建实例时使用lambdas:
Button myButton([](int &a){a++;}, [](int &a){a--;});
实例
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针