【问题标题】:How to get the arguments binded into boost::function?如何将参数绑定到 boost::function 中?
【发布时间】:2013-02-15 14:30:10
【问题描述】:

来自 boost::bind 文档(http://www.boost.org/doc/libs/1_53_0/libs/bind/bind.html#with_functions),“bind 接受的参数由返回的函数对象在内部复制和保存”,但如果有办法我可以在这些函数对象中复制参数?

即:

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <string>

using namespace std;

void doSomthing(std::string str)
{
}

int main()
{    
    boost::function<void(void)> func_obj = boost::bind(&doSomthing, "some string");
    //how can I get the std::string argument("some string") through func_obj?
}

提前致谢。

【问题讨论】:

  • 你的意思是你想从你的 func_objc 变量中读取它们?不太可能。
  • 是的,我就是这个意思。
  • 我们现在有 boost 1. 53,而不是 1.35。
  • 抱歉,只是解决这个问题,但并不重要。

标签: c++ boost boost-bind boost-function


【解决方案1】:

除了调用 Boost.Function 对象外,您并不能做太多事情——这是设计使然。 (你可以复制它,销毁它,与 NULL 比较,但仅此而已)。

考虑以下代码:

void Foo () {}
void Bar ( int i ) { printf ( "%d", i ); }

boost::function<void(void)> fFoo (Foo);
boost::function<void(void)> fBar = boost::bind (Bar, 23);

这两个对象被设计为同等对待。它们是相同的类型,并且行为相同。 boost函数中没有区分它们的机制。

有关 Boost.Function(和其他地方)中使用的技术的详细描述,请查看 Nevin Liber 的 type erasure talk from Boostcon 2010

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 2013-07-13
    • 2013-12-14
    • 1970-01-01
    相关资源
    最近更新 更多