gpt4 book ai didi

c++ - 求一个boost::bind()的限制的例子

转载 作者:行者123 更新时间:2023-11-30 04:29:44 24 4
gpt4 key购买 nike

我阅读了限制的解释 http://www.boost.org/doc/libs/1_49_0/libs/bind/bind.html#Limitations但我不太明白。任何机构都可以给我一个说明限制的例子吗?

让我用这个例子以另一种方式问这个问题:

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
#include <string>
using namespace std;

void Five(int &a, int &b, int &c, const int &d, const int &e) {
cerr << "In Five(): " << a + b + c + d + e << endl;
}

int main() {
int r = 1;
const int c = 100;

boost::bind(Five, _1, _2, _3, _4, _5)(r, r, r, c, r);
boost::bind(Five, _1, _2, _3, _4, _5)(r, r, r, r, c);

return 0;
}

这段代码编译得很好(没有 C++11 支持)。那么,如果 bind 在这种情况下甚至有效,那么“限制”指的是什么?有具体的例子吗?

另一个(更好的)例子:

#include <boost/bind.hpp>
#include <iostream>
#include <string>
using namespace std;

void Two(int &a, const int &c) {
cerr << "In Two(): " << a + c << endl;
}

void Three(int &a, int &b, const int &c) {
cerr << "In Three(): " << a + b + c << endl;
}

int Fun() { return 3; }

int main() {
int r = 1;
const int c = 100;
boost::bind(Two, _1, _2)(r, Fun()); // 1. OK
boost::bind(Three, _1, _2, _3)(r, r, c); // 2. OK
Three(r, r, Fun()); // 3. OK
boost::bind(Three, _1, _2, _3)(r, r, Fun()); // 4. CE!!
//??? Why 2 is OK but 4 is not ???

return 0;
}

最佳答案

限制是指“完美转发”,这是通过启用 c++0x 在最近的编译器上实现的(在编译时可能需要一些选项)。

因此,如果您的编译器支持 c++0x,那么 boost::bind 使用完美转发,否则请忽略该问题以避免函数重载爆炸!

例如:当使用 2 个参数绑定(bind)函数时,由 boost::bind 创建的仿函数对象将需要所有这些重载(如果没有 c++0x 支持):

operator()(const A&, const B&)
operator()(const A&, B&)
operator()(A&, const B&)
operator()(A&, B&)

完美转发。

这是一个详细描述完美转发问题的链接:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2002/n1385.htm

不完美的转发将最终导致您:

  • 非 const 或 const 引用解决方案(如 boost::bind)的编译错误
  • 按值解决方案中的意外拷贝

关于c++ - 求一个boost::bind()的限制的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9155106/

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