假设您这样定义回调函数:
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 函数绑定(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
它不使用函数或绑定(bind)函数,但它确实传递指针参数并执行我需要的操作。我不跳过绑定(bind)函数的原因是因为我试图将函数存储在一个类(私有(private))中,如果它是一个模板,我不能存储它,因为它是用类创建的。
上面产生的错误来自这段代码:
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)>'
这可能吗?提前致谢。
最佳答案
您可以为未绑定(bind)的参数包含一个占位符:
std::bind(&Main::ImAFunction, this, std::placeholders::_1);
如果您觉得有点冗长,lambda 可能更具可读性:
[this](float a){ImAFunction(a);}
关于不带参数的 C++ 存储函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26269483/