在C++ 11之前我使用过boost::bind或者boost::lambda很多.该bind部分使其成为标准库(std::bind),另一部分成为核心语言(C++ lambdas)的一部分,并使lambdas的使用变得更加容易.如今,我几乎没用std::bind,因为我几乎可以用C++ lambdas做任何事情.std::bind我可以想到一个有效的用例:
struct foo
{
template < typename A, typename B >
void operator()(A a, B b)
{
cout << a << ' ' << b;
}
};
auto f = bind(foo(), _1, _2);
f( "test", 1.2f ); // will print "test 1.2"
Run Code Online (Sandbox Code Playgroud)
相当于C++ 14的等价物
auto f = []( auto a, auto b ){ cout << a << ' ' << b; }
f( "test", 1.2f …Run Code Online (Sandbox Code Playgroud) 我有一个关于哪种样式是首选的问题:std :: bind Vs lambda在C++ 0x中.我知道它们服务于某些不同的目的,但我们举一个交叉功能的例子.
使用lambda:
uniform_int<> distribution(1, 6);
mt19937 engine;
// lambda style
auto dice = [&]() { return distribution(engine); };
Run Code Online (Sandbox Code Playgroud)
使用bind:
uniform_int<> distribution(1, 6);
mt19937 engine;
// bind style
auto dice = bind(distribution, engine);
Run Code Online (Sandbox Code Playgroud)
我们应该选择哪一个?为什么?假设与上述示例相比情况更复杂.即一个优于另一个的优点/缺点是什么?