C++ 11 std :: bind和boost :: bind之间的区别

Haa*_*hii 66 c++ boost boost-bind stdbind c++11

这两者有什么区别吗?还是我的安全,以取代所有出现boost::bindstd::bind在我的代码,从而消除对加速的依赖?

ild*_*arn 86

  • boost::bind 有重载的关系运算符,std::bind没有.

  • boost::bind 支持非默认调用约定,std::bind不保证(标准库实现可以提供此作为扩展).

  • boost::bind提供了一种直接机制,允许一个人阻止对嵌套绑定表达式(boost::protect)的急切评估std::bind.(也就是说,可以使用boost::protectstd::bind如果他们愿意,或平凡重新实现它自己.)

  • std::bind提供了一种直接机制,允许人们将任何用户定义的函子视为嵌套的绑定表达式,以强制进行急切评估(std::is_bind_expression:[func.bind.isbind]/1,[func.bind.bind]/10),boost::bind但不是.


orm*_*orm 24

除了其他答案中引用的几个差异外,还有两个不同之处:

  • boost::bind似乎在某些情况下处理重载的函数名称,std::bind而不是以相同的方式处理它们.请参阅 c ++ 11常见问题解答

(使用gcc 4.7.2,boost lib version 1_54)

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
Run Code Online (Sandbox Code Playgroud)

所以,如果你简单地更换所有boost::bindstd::bind,您的构建可能会断裂.

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

(使用gcc 4.7.2,boost lib version 1_54)

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);
Run Code Online (Sandbox Code Playgroud)

所以,如果你简单地更换所有std::bindboost::bind,您的构建也突破.


Igo*_* R. 16

除了上面列出的,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

  • 标准中的`INVOKE`功能适用于任何支持`operator*`的智能指针 (2认同)

111*_*111 8

我没有完整的答案,但std::bind会使用可变参数模板而不是参数列表.

占位符位于全局命名空间中std::placeholders,std::placeholders::_1而不是全局命名空间中.

我将命名空间别名为stdph with

namespace stdph=std::placeholders;
Run Code Online (Sandbox Code Playgroud)

除此之外,我在更新到C++ 11时没有遇到任何问题

  • @goertzenator:我认为问题更多的是使用任何_other_ Boost库,因为我要求至少三分之一的Boost直接或间接使用`boost :: bind`. (2认同)