在C++11之前,我经常使用boost::bind
或boost::lambda
。其中的bind
部分已成为标准库的一部分(std::bind
),而另一个部分则成为核心语言(C++ lambda)的一部分,并且大大简化了Lambda表达式的使用。现在,我几乎不再使用std::bind
,因为我可以用C++ Lambda表达式实现几乎任何功能。我能想到只有一个有效的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"
对应C++14的代码为:
auto f = []( auto a, auto b ){ cout << a << ' ' << b; }
f( "test", 1.2f ); // will print "test 1.2"
更加简短和简洁。(在C++11中,由于自动参数的原因,这种方法尚不可行。)除了使用std::bind
而不是C++ lambda之外,还有其他有效的用例吗?或者说,在C++14中,std::bind
是否已经变得多余了?
bind
。 - Bartek Banachewiczbind
。只需使用auto f = foo {};
即可。 - aschepler