C++存储不带参数的函数

C++ Store Function without Argument

本文关键字:函数 参数 存储 C++      更新时间:2023-10-16

假设您定义了这样一个回调函数:

typedef std::function<void(float)> Callback;

你有一个这样的功能:

void ImAFunction(float a)
{
    //Do something with a
}

有没有一种方法可以在没有参数的情况下存储函数,然后在以后将其传递给它?

例如:

//Define the Callback storage
Callback storage;
storage = std::bind(ImAFunction, this);
//Do some things
storage(5);

这不起作用,我在下面用我的一些真实代码解释了这一点。

如果我用std::bind函数绑定值,我可以接近我所不希望的。例如:

//Change
//storage = std::bind(ImAFunction, this);
storage = std::bind(ImAFunction, this, 5.0); //5.0 is a float passed

这是有效的,但当我通过函数传递值时,结果是我之前设置的值:

storage(100); //Output is still 5

我基于这篇文章认为这是可能的。

http://www.cprogramming.com/tutorial/function-pointers.html

它不使用函数或绑定函数,但它确实传递指针参数并执行我所需要的操作。我之所以不跳过绑定函数,是因为我试图将函数存储在类(私有)中,如果它是模板,我就无法存储它,因为它是用类创建的。

上面产生的错误来自这个代码:

struct BindInfo {
    Callback keyCallback;
    int bindType;
    bool isDown;
    bool held;
    std::string name;
};
template <class T1>
void bindEvent(int bindType, T1* keydownObj, void(T1::*keydownF)(float), std::string name)
{
    BindInfo newKeyInfo = { std::bind(keydownF, keydownObj), bindType, false, false, name };
    inputBindings.insert(std::pair<int, BindInfo>(BIND_NULL, newKeyInfo));
};

错误为:

No viable conversion from '__bind<void(Main::*&)(float), Main *&>' to 'Callback' (aka 'function<void (float)>'

这可能吗?提前谢谢。

您可以为未绑定参数包含占位符:

std::bind(&Main::ImAFunction, this, std::placeholders::_1);

如果你发现这有点晦涩,lambda可能更可读:

[this](float a){ImAFunction(a);}

听起来你要找的是一个函数指针。虽然我在C++中使用它们的经验不多,但我在C中使用过它们,所以:是的,这是可能的。也许是这样的:

void (*IAmAFunctionPointer)(float) = &IAmAFunction;

考虑这一行的最佳方式是,IAmAFunctionPointer是一个指针(因此是*),它返回一个void,并取一个float。随后:

float a = 5;
IAmAFunctionPointer(a);

您甚至可以将其设计为将回调函数传递到方法中(我认为这就是您想要的)。

    void DoStuffThenCallback(float a, void (*callback)(float))
    {
     //DoStuff
     callback(a);
    }

进一步阅读:http://www.cprogramming.com/tutorial/function-pointers.html