[英]std::bind on member with call operator
This might be a silly and stupid thing to do - however I would like to understand what happens here. 这可能是一个愚蠢和愚蠢的事情 - 但我想了解这里发生了什么。
I have the following code: 我有以下代码:
#include <iostream>
#include <functional>
namespace
{
struct call
{
void operator()() const
{
std::cout << "call::operator()" << std::endl;
}
};
struct dummy
{
dummy() = default;
dummy(const dummy&) = delete;
call member;
};
}
So member essentially would work like any other object method, allowing it to be invoked as: 因此,member本质上可以像任何其他对象方法一样工作,允许它被调用为:
dummy d;
d.member()
Which would print call::operator()
. 哪个会打印call::operator()
。
Now I would like to use bind to do that, the initial implementation looked like this: 现在我想使用bind来做到这一点,初始实现看起来像这样:
int main()
{
dummy d;
auto b = std::bind(&dummy::member, &d);
b();
return 0;
}
This compiles, but nothing is printed. 编译,但没有打印。 I don't really understand what is happening - the fact that it compiles, but produces no output puzzles me :) surely some magic is going on inside the belly of std::bind
, but what? 我真的不明白发生了什么 - 它编译的事实,但产生没有输出困惑我:)当然std::bind
的肚子里面有一些魔法,但是什么?
Here is a link to play with the code: https://ideone.com/P81PND 以下是使用代码的链接: https : //ideone.com/P81PND
Currently, your bind return a member, so b()
is d.member
. 目前,您的绑定返回一个成员,因此b()
是d.member
。 You would have to call operator () on that: 您必须在上面调用operator():
b()(); // call::operator()
As alternative, you may use any of: 或者,您可以使用以下任何一项:
b = std::bind(&call::operator(), &d.member);
b = [&]() {d.member();};
You can also call through a std::reference_wrapper
. 您也可以通过std::reference_wrapper
调用。 No need for bind
at all. 根本不需要bind
。
int main()
{
dummy d;
auto b= std::cref(d.member); // create reference wrapper
b();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.