Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

c++ - Role of placeholder in Boost::bind in the following example

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 << "
";
}

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

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

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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)

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

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.

In your particular case, the 2 uses are equivalent.

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."

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...