C 存储功能作为变量即时
C++ Store function as Variable on the fly
我想知道是否有任何方法可以将函数创建为变量或可以随时更改类的函数。以下是一些示例来表明我的意思
java
Thread t = new Thread() {
public void run() {
//do something
}
}
javascript
var f = function() {
//do something
}
我知道您可以将预定义函数用作变量,但是我希望完全在函数中执行此操作。
c 是一种编译语言。因此,您不能"随时更改班级的功能"。只有解释的语言才能做到这一点。
这是您可以在C 中做的一两件事:
#include <functional> // For std::function
bool IsGreaterThan(int a, int b)
{
return a > b;
}
int main()
{
// 1. Create a lambda function that can be reused inside main()
const auto sum = [](int a, int b) { return a + b;};
int result = sum(4, 2); // result = 6
// 2. Use std::function to use a function as a variable
std::function<bool(int, int)> func = IsGreaterThan;
bool test = func(2, 1); // test = true because 2 > 1
}
在第二个示例中,我们创建了一个函数指针,该指针将参数二进 int
并返回bool
。使用std ::函数的好处是,只要有相同的参数和返回值,就可以将指针与函数指针混合使用。
编辑:以下是如何使用std :: function and std :: bind。
bool IsGreaterThan(int a, int b)
{
return a > b;
}
typedef bool(*FunctionPointer)(int, int); // Typedef for a function pointer
// Some class
struct SomeClass
{
private:
vector<FunctionPointer> m_functionPointers;
vector<std::function<bool(int, int)>> m_stdFunctions;
public:
SomeClass()
{
// With regular function pointers
m_functionPointers.push_back(IsGreaterThan);
m_functionPointers.push_back(&this->DoSomething); // C2276: '&' : illegal operation on bound member function expression
// With std::function
m_stdFunctions.push_back(IsGreaterThan);
m_stdFunctions.push_back(std::bind(&SomeClass::DoSomething, this, std::placeholders::_1, std::placeholders::_2)); // Works just fine.
}
bool DoSomething(int a, int b) { return (a == b); }
};
相关文章:
- 为什么我可以将变量存储在不是其最小对齐方式的倍数的地址?
- 如何将变量存储为无
- 有没有办法强制C++编译器将变量存储在寄存器中?
- C++ - thread_local变量存储在哪里?
- 如何使用 c++ 将多个变量存储在一个变量中?例如,双精度 x,y,z 包含在可变点 p 中
- 如何将文件从文件作为变量存储
- 引用变量存储在哪里
- 尝试在C 程序中设置简单的键盘输入.使用变量存储True或false
- 如何将变量存储在另一个文件中
- 编译时局部变量存储在哪里
- lambda 捕获的变量存储在哪里
- 闭包捕获的变量存储在哪里?
- 静态和全局变量存储说明
- 模式名称,将值作为静态变量存储在函数中
- 任何人都能解释常量或常量变量存储在哪里吗
- 将变量存储在将被多次使用的函数中的最佳方式(c++)
- 如何将字符变量存储为二维字符变量
- 将环境变量存储在动态分配的数组中
- 从矢量中获取选定的数据,然后作为变量存储
- DLL的全局变量存储在内存中