C 存储功能作为变量即时

C++ Store function as Variable on the fly

本文关键字:变量 存储 功能      更新时间:2023-10-16

我想知道是否有任何方法可以将函数创建为变量或可以随时更改类的函数。以下是一些示例来表明我的意思

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); }
};