在以下示例中,占位符在Boost :: bind中的作用 [英] Role of placeholder in Boost::bind in the following example

查看:199
本文介绍了在以下示例中,占位符在Boost :: bind中的作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多关于使用占位符的SO的例子,但我仍然有点困惑,如果有人可以解释以下两个语句之间的区别,将非常感谢。

There are numerous example on SO regarding the use of placeholders however I am still a little bit confused and would appreciate it if someone could explain the difference between the following two statements

void SomeMethod(int a)
{
    std::cout << "Parameter pass " << a << "\n";
}

Statement 1 : boost::bind(&SomeMethod,_1)(12);

Statement 2 : boost::bind(&SomeMethod,12)();



我相信我理解语句1是链接。 boost :: bind(& SomeMethod,_1)的输出具有附加到它的参数12。但是我很难理解语句2中发生了什么。如果一个参数可以直接使用boost :: bind(如语句2),那么为什么需要一个占位符?

I believe I understand statement 1 which is chaining. The output of boost::bind(&SomeMethod,_1) gets to have a parameter of 12 attached to it. However I have difficulty understanding whats happening in statement 2. If a parameter could be passed directly using boost::bind (as in statement 2) then why the need of a placeholder ?

推荐答案

占位符的使用之一是更改特定函数的参数顺序

One of uses of placeholders is to change the arguments order of a particular function

示例来自boost。假设您以前有 f(x,y) g(x,y,z)

Example taken from boost . Assume you previously have f(x, y) and g(x,y,z). Then

bind(f, _2, _1)(x, y);                 // f(y, x)    
bind(g, _1, 9, _1)(x);                 // g(x, 9, x)    
bind(g, _3, _3, _3)(x, y, z);          // g(z, z, z)    
bind(g, _1, _1, _1)(x, y, z);          // g(x, x, x)

有趣的是注意下面的BOOST指南语句最后一个例子

It is interesting to note the following BOOST guide statement about the last example


请注意,在最后一个例子中,bind(g,_1,_1,_1)包含对第一个参数之外的任何参数的引用,但它仍然可以与多个参数一起使用。

Note that, in the last example, the function object produced by bind(g, _1, _1, _1) does not contain references to any arguments beyond the first, but it can still be used with more than one argument. Any extra arguments are silently ignored, just like the first and the second argument are ignored in the third example.

我认为很清楚,我们可以清楚地看到第一个参数和第二个参数被忽略。现在占位符使这种替换更干净,更优雅。

I think it is clear now that placeholders make this kind of replacement cleaner and more elegant.

在您的特定情况下,2个用法是等效的。

In your particular case, the 2 uses are equivalent.


可以选择性地只绑定一些参数。 bind(f,_1,5)(x)等价于f(x,5);这里的_1是一个占位符参数,表示用第一个输入参数替换

It is possible to selectively bind only some of the arguments. bind(f, _1, 5)(x) is equivalent to f(x, 5); here _1 is a placeholder argument that means "substitute with the first input argument."

另一个很好的占位符是当你有很多的参数,你只想绑定其中之一。示例:imagine h(a,b,c,d,e,f,g),你只需要绑定第6个参数!

Another good use of placeholders is when you have lots of arguments and you only want to bind one of them. Example: imagine h(a,b,c,d,e,f,g) and you just want to bind the 6th argument!

这篇关于在以下示例中,占位符在Boost :: bind中的作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆