绑定到成员变量
我对绑定到成员变量时 boost::bind 的作用感到困惑。 通过绑定到成员函数,我们本质上创建了一个函数对象,然后调用它并向其传递通过占位符提供或延迟和替换的参数。
但是这个表达式在幕后做了什么:
boost::bind(&std::pair::second, _1);
用什么来代替占位符 _1?
我在阅读有关 boost::bind 的文章中的示例时发现了这一点:
void print_string(const std::string& s) {
std::cout << s << '\n';
}
std::map<int,std::string> my_map;
my_map[0]="Boost";
my_map[1]="Bind";
std::for_each(
my_map.begin(),
my_map.end(),
boost::bind(&print_string, boost::bind(
&std::map<int,std::string>::value_type::second,_1)));
I am confused as to what boost::bind does when we bind to member variables. With binding to member function, we essentially create a function object, and then call it passing to it the arguments that are provided or delayed and substituted via placeholders.
But what does this expression do behind the scenes:
boost::bind(&std::pair::second, _1);
What gets substituted in place of the placeholder _1?
I found this while reading this example from an article on boost::bind:
void print_string(const std::string& s) {
std::cout << s << '\n';
}
std::map<int,std::string> my_map;
my_map[0]="Boost";
my_map[1]="Bind";
std::for_each(
my_map.begin(),
my_map.end(),
boost::bind(&print_string, boost::bind(
&std::map<int,std::string>::value_type::second,_1)));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它在幕后使用成员指针并将其应用于传入的参数。 在绑定上下文中它相当复杂,因此这里是一个指向成员使用的指针的简单示例:
绑定在幕后组合不同的调用。 生成的函子采用 std::map<>::iterator 的取消引用(类型为 std::pair< const key_type, value_type >)。 它被传递到内部绑定,该内部绑定取消引用成员指针,从而将
(*it).second
返回到外部绑定,该外部绑定将该值传递给print_string
方法最终调用:print_string( (*it).second )
。(*it)
实际上是您询问的_1
。 所有_#
都是占位符,也就是说,bind 的结果将是一个函子,该函子将采用与占位符数量定义的顺序存在的不同占位符一样多的参数。 在您给出的示例中,生成的函子采用单个参数_1
。Behind the scenes it is using a member pointer and applying it to the passed in argument. It is quite complex in the context of binds, so here is a simple example of pointer to member usage:
Behind the scenes bind is composing different calls. The resulting functor takes the dereference of std::map<>::iterator (of type std::pair< const key_type, value_type >). That is passed to the inner bind, that dereferences the member pointer, thus returning
(*it).second
to the outer bind that passes that value to theprint_string
method for the final call:print_string( (*it).second )
.(*it)
is actually the_1
you asked about. All_#
are placeholders, that is, the result of bind will be a functor that will take as many arguments as different placeholders exist in the order defined by the number of placeholder. In the example you gave, the resulting functor takes a single argument_1
.功能上等同于
ie。 它是一个将
对
映射到其第二个
成员的函数(对象)。is functionally equivalent to
ie. it is a function (object) that maps a
pair<U,V>
to itssecond
member.