|
某网站的C/C++面试题精选
C++面试题:bind1st的函数配接器的实现
考点:理解函数配接器的实现
出现频率:★★★
标准C++模板库中有一个名为bind1st的函数配接器(实际就是一个函数模板),它接受两个参数,一个是二元函数对象bin_op,一个是二元函数对象的参数value。返回一个新的一元函数对象uni_op。在使用uni_op(param)等效于bin_op(value,param)。即二元函数对象的第一个value被“固定”了。
试编写程序实现一个类似功能的my_bind1st函数配接器,并给出相应的测试代码。
解析:
程序代码如下:
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
template <class Operation, class Param>
class my_binder1st
{
public:
my_binder1st(Operation op, Param first)
{
m_op = op; //二元函数对象赋值
m_first = first; //绑定的参数赋值
}
Param operator () (Param second) //重载()运算符
{
return m_op(m_first, second); //返回二元函数对象执行结果
}
private:
Operation m_op; //二元函数对象
Param m_first; //绑定的第一个参数
};
template <class Operation, class Param>
my_binder1st<Operation, Param>
my_bind1st(Operation op, Param first)
{
//返回一个新的一元函数对象
return my_binder1st<Operation, Param>(op, first);
}
int main()
{
//plus的第一个参数为10
my_binder1st<plus<int>, int> plusObj = my_bind1st(plus<int>(), 10);
//minus的第一个参数为10
my_binder1st<minus<int>, int> minusObj = my_bind1st(minus<int>(), 10);
cout << plusObj(20) << endl; //执行10 + 20,打印30
cout << minusObj(20) << endl; //执行10 - 20,打印10
return 0;
}
程序中类模板my_binder1st重载了“()”运算符并且只有一个参数second(代码17行),因此它是一个一元函数对象。my_binder1st有两个私有成员,一个是二元函数对象op,另一个是绑定的第一个参数first。这两个私有成员是通过构造函数被赋值的。
函数模板my_bind1st用来得到一个my_binder1st模板类对象,通过把二元函数对象以及绑定的first参数传入,得到转换之后的一元函数对象。
最后main函数中对my_bind1st进行了测试,从代码39和40行的打印结果可以看出,plusObj和minusObj确实转换成功。
跟多面试题请参考爱学网izixue |
|