首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >boost std::bind与C++11::bind的区别

boost std::bind与C++11::bind的区别
EN

Stack Overflow用户
提问于 2012-05-12 00:56:04
回答 4查看 21.4K关注 0票数 68

这两者之间有什么区别吗?或者,在代码中将每次出现的boost::bind都替换为std::bind,从而消除对Boost的依赖,这样做安全吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-05-12 01:13:33

  • boost::bind绑定,not.
  • boost::bind supports non-default calling conventionsstd::bind不保证(标准库实现可以提供这一点,因为not.
  • boost::bind提供了一种直接机制来防止对嵌套绑定表达式(supports non-default calling conventions)的急于求值,而std::bind不是这样的。(也就是说,如果需要,可以将boost::protectstd::bind一起使用,或者在他们的own.)
  • std::bind上简单地重新实现它提供了一种直接机制,允许人们将任何用户定义的函数式视为嵌套绑定表达式,以便强制执行急于求值(std::is_bind_expression:func.bind.isbind/1,func.bind.bind/10),而boost::bind不这样做。
票数 87
EN

Stack Overflow用户

发布于 2013-08-07 08:36:25

除了其他答案中提到的几个差异外,这里还有另外两个差异:

在某些情况下,

  • boost::bind似乎可以处理重载的函数名,而std::bind则不能以同样的方式处理它们。请参阅c++11 faq

(使用gcc 4.7.2,boost库版本1_54)

代码语言:javascript
复制
void foo(){}
void foo(int i){}

auto badstd1 = std::bind(foo);  
//compile error: no matching function for call to bind(<unresolved overloaded function type>)
auto badstd2 = std::bind(foo, 1); 
//compile error: no matching function for call to bind(<unresolved overloaded function type>)
auto std1 = std::bind(static_cast<void(*)()>(foo)); //compiles ok
auto std2 = std::bind(static_cast<void(*)(int)>(foo), 1); //compiles ok
auto boost1 = boost::bind(foo, 1); //compiles ok
auto boost2 = boost::bind(foo); //compiles ok

因此,如果您只是简单地将所有boost::bind替换为std::bind,您的构建可能会中断。

  • std::bind可以无缝绑定到c++11 lambda类型,而Boost1.54的boost::bind似乎需要用户输入(除非定义了return_type )。请参阅boost doc

(使用gcc 4.7.2,boost库版本1_54)

代码语言:javascript
复制
auto fun = [](int i) { return i;};
auto stdbound = std::bind(fun, std::placeholders::_1);
stdbound(1);

auto boostboundNaive = boost::bind(fun, _1);  //compile error.
// error: no type named ‘result_type’ ...
auto boostbound1 = boost::bind<int>(fun, _1); //ok
boostbound1(1);
auto boostbound2 = boost::bind(boost::type<int>(), fun, _1); //ok
boostbound2(1);

因此,如果您只是简单地将所有std::bind替换为boost::bind,那么您的构建也可能会中断。

票数 24
EN

Stack Overflow用户

发布于 2012-05-13 17:54:32

除了上面列出的,boost::bind还有一个重要的扩展点: get_pointer()函数,它允许将boost::bind与任何智能指针集成,例如。ATL::CComPtr等http://www.boost.org/doc/libs/1_49_0/libs/bind/mem_fn.html#get_pointer

因此,使用boost::bind还可以绑定weak_ptr:http://lists.boost.org/Archives/boost/2012/01/189529.php

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10555566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档