std::bind 和 std::function 重叠或互补
std::bind and std::function overlap or complementary?
我在这里看这个示例,结合 std::bind 和 std::function 以创建一个命令:真的很整洁!命令类的代码如下所示:
class Command
{
private:
std::function<void ()> _f;
public:
command() {}
command(std::function<void ()> f) : _f(f) {}
template <typename T> void setFunction (T t) {_f = t ;}
void execute()
{
if(!_f.empty())
_f();
}
};
假设我有一个包含成员函数的类MyClass
:
class MyClass
{
public:
void myMemberFn() {}
}
然后调用代码如下所示:
MyClass myClass;
command(std::bind(&MyClass::myMemberFn, myClass));
虽然我必须承认,我真的不明白为什么除了std::bind
之外还需要std::function
.在我看来,绑定已经封装了函数调用,那么为什么Command
需要函数呢?Command
不能存储std::bind
而不是std::function
吗?
我一直在查看标准::绑定和标准::函数的文档,但没有得到它......
有人知道为什么需要std::function
吗?
绑定和标准::函数~=提升::函数
您必须将
std::bind
表达式的结果存储在某个地方。标准未指定 std::bind
本身的返回类型,因此您无法创建该类型的命名成员变量(不过,您可以使用 C++11 auto
来创建这样的局部变量!
此外,任何采用std::function
的函数都可以(由于隐式转换std::function
)接受各种可调用对象,而不仅仅是std::bind
结果 - 您可以向其传递常规函数指针、lambda、自定义函数对象,任何可以调用的内容。
从绑定文档,
A function object of unspecified type T, for which std::is_bind_expression<T>::value == true,
and which can be stored in std::function.
所以
std::function<void ()> _f;
需要存储 的返回值
command(std::bind(&MyClass::myMemberFn, myClass));
以便以后可以实际调用它。
相关文章:
- Confusion: decltype vs std::function
- 为什么 std::function 可以作为 std::not2 的参数?
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 传递给std::function template的template参数究竟代表什么
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 将函数包装器转换为 std::function
- 类型擦除的std::function与虚拟函数调用的开销
- C++ std::function 对于类 exept 的所有实例都是空的(只有 Visual2019 编译器问题)
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- 将 lambda 表达式传递给 std::function in C++
- 模板类的部分模板专用化,如 std::function
- 可变参数模板参数扩展 类型为 std::function 的类成员
- 从 std::function in C++ 访问模板化 lambda
- 什么是 std::function::argument_type 的替代品?
- C++派生类重载函数(带有 std::function 参数)不可见
- 如何在 qi 符号表中使用 std::function
- 将 std::function 与模板一起使用
- C++ 事件管理器的回调,使用 std::function 和 std:bind 以及派生类作为参数
- 我需要在 std::function 上使用 unique_ptr 吗?
- 如何将函数指针从 std::function 传递到 Linux 克隆?