【发布时间】:2013-12-24 09:07:48
【问题描述】:
我在看this exemple here,结合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。在我看来,bind 已经封装了函数调用,那为什么Command 中还需要函数呢?不能Commandstore std::bind 而不是std::function?
我一直在查看 std::bind 和 std::function 的文档,但没有得到它......
有人知道为什么需要std::function吗?
PS: 我假设 std::bind ~= boost::bind 和 std::function ~= boost::function
【问题讨论】:
-
std::bind是一个 function 模板,可用于复制初始化或分配给std::function,这是一个 class 模板。 -
setFunction作为非模板void setFunction(std::function<void()> t) {_f = std::move(t);}会更好。它并不比模板版本贵,而且由于move,它可能更便宜。 -
@Casey:很好的提示,谢谢!