C++存储不带参数的函数
C++ Store Function without Argument
假设您定义了这样一个回调函数:
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
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数