【问题标题】:boost::bind as l-value objectboost::bind 作为左值对象
【发布时间】:2011-09-16 11:42:36
【问题描述】:

有没有办法做这样的事情(MS VS 2008)?

boost::bind mybinder = boost::bind(/*something is binded here*/);
mybinder(/*parameters here*/); // <--- first call
mybinder(/*another parameters here*/); // <--- one more call

我试过了

int foo(int){return 0;}

boost::bind<int(*)(int)> a = boost::bind(f, _1);

但它不起作用。

【问题讨论】:

  • “它不起作用”是什么意思?
  • 请接受一些以前的答案。您来这里已经一年多了,这对于了解 SO 的工作原理已经绰绰有余了。

标签: c++ functor boost-bind lvalue


【解决方案1】:
int foo(int){return 0;}
boost::function<int(int)> a = boost::bind(f, _1);

【讨论】:

  • 这也不对。 a 应该可以直接等同于 foo 作为函数指针——这里不需要绑定。
  • 我收到“错误 C2079:'a' 使用未定义的类 'boost::function'”
  • @fogbit:那你没有#includeboost.function。
  • @DeadMG:我知道这不是必需的,但也不是“不正确”。我选择了最接近原始代码的解决方案。如果您想更进一步,OP 可以用整数文字 0 替换对 a 的整个调用。
【解决方案2】:

绑定返回未指定的类型,所以不能直接创建该类型的变量。然而,有一个类型模板boost::function 可以为任何函数或仿函数类型构造。所以:

boost::function<int(int)> a = boost::bind(f, _1);

应该可以解决问题。另外,如果您不绑定任何值,仅绑定占位符,则可以完全不使用 bind,因为 function 也可以从函数指针构造。所以:

boost::function<int(int)> a = &f;

只要fint f(int) 就应该有效。该类型以 std::function 的形式进入 C++11,可与 C++11 闭包一起使用(以及 bind,这也被接受):

std::function<int(int)> a = [](int i)->int { return f(i, 42); }

注意,在 C++11 中直接调用它,auto 的新用法更容易:

auto a = [](int i)->int { return f(i, 42); }

但如果你想传递它,std::function 仍然可以派上用场。

【讨论】:

  • 如果你使用 C++11 和 lambdas,你应该使用std::function
  • @Tomalak:我扩展了 C++11 部分并切换到 std:: 那里。
猜你喜欢
  • 1970-01-01
  • 2013-01-15
  • 2013-09-21
  • 2011-12-07
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多