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

标签 c++ boost

我阅读了限制的解释 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/

相关文章:

c++ - 使用 boost::async_connect 问题

java - Android的OCR应用程序

c++ - 单词大写的最快方法

c++ - 迭代器是否分配指针等内存?

c++ - 重载运算符的模板 : error: overloaded 'operator*' must have at least one parameter of class or enumeration type

c++ - "candidate template ignored: substitution failure:"编译错误?

c++ - 令人困惑的部分模板特化

c++ - 对 Boost JSON 解析器的调用永远不会返回

c++ - 在 C 中,当管道输入到另一个程序时,它无法打开

c++ - 如何在适用于英特尔 Iris Pro 的 Mac OSX 10.9.4 上获取 OpenCL C++ 绑定(bind)