在定义一个仿函数(functor)不会使用binary_function,但是如果需要函数适配器便需要使用它实现:
struct Inserter
{
void operator() (int n, vector<int>& v)
{
v.push_back(n);
}
}
Inserter cIn;
vector<int> vInt;
cln(2, vInt);
通过一个算法忘当前容器追加值:
template<typename Functor>
void append(Functor f)
{
int x;
while(cin >> x)
f(x);
}
此时,append的Functor只有一个形参,在不考虑重写Inserter的基础上我们需要定义Inserter_adapter:
template<typename Functor>
struct Inserter_Adapter
{
Inserter_Adapter(const Functor& f, vector<int>& v)
:_f(f), _v(v)
{}
void operator()(int x)
{
_f(x, v_);
}
private:
Functor& _f;
vector<int> _v;
};
//使用:
Inserter cIn;
vector<int> vIn;
Inserter_Adapter cIna(f, vIn);
append(ia);
在STL中,提供了相关的函数 bind2nd的适配器,把第二个参数绑定让一个二元函数变成一元的。 此前定义的Inserter不能直接使用在bind2nd上,因为和bind2nd的concept不符合,需要继承binary_function:
struct Inserter : public std::binary_function<int, vector<int>&, void>
{
void operator()(int x, vector<int>& vIn)
{
v.push_back(x);
}
}
Inserter cIn;
vector<int> vIn;
append(std::bind2nd(cIn, vd)) //1
Inserter_Adapter(cIn, vd)