gpt4 book ai didi

c++ - Boost::bind 中占位符的作用如下例

转载 作者:行者123 更新时间:2023-11-30 01:57:28 30 4
gpt4 key购买 nike

SO 上有很多关于占位符使用的示例,但是我仍然有点困惑,如果有人能解释以下两个语句之间的区别,我将不胜感激

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 中所示),那么为什么需要占位符?

最佳答案

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

取自 boost 的示例。假设您之前有 f(x, y)g(x,y,z)。然后

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 指南声明

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.

我认为现在很清楚,占位符使这种替换更干净、更优雅。

在您的特定情况下,这两种用法是等效的。

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

占位符的另一个很好的用途是当你有很多参数并且你只想绑定(bind)其中一个时。示例:假设 h(a,b,c,d,e,f,g) 而您只想绑定(bind)第 6 个参数!

关于c++ - Boost::bind 中占位符的作用如下例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18680607/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com