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

标签 c++ callback function-pointers

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

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/

相关文章:

c++ - 'This'指针与Vtable函数的关系

c++ - 使用 winapi 搜索隐藏文件

c++ - fftw C++ 来自幅度和相位数组的逆二维 FFT

c - makecontext函数指针[错误: invalid use of void expression]

c++ - 如何在 C++17 中将抛出函数指针静态转换为 noexcept?

c++ - 是否可以使用 SFML 绘制曲线?

node.js - 如何在没有回调的情况下返回 Mongoose 查询结果

c++ - 如何实现从C++函数到Swift的回调

node.js - 代码模式相当于 Node JS 中阻塞条件下的链式 if/elseif?

javascript - WebAssembly 中 call_indirect 的错误结果