Item 35: Consider alternatives to virtual functions.
https://github.com/wangcy6/weekly/blob/master/reading-notes/STL%E6%BA%90%E7%A0%81%E5%89%96%E6%9E%90/stl.md
小王职场记 谈谈你的STL理解(1) c++系列之二 指向成员函数的指针(烧脑)
function object
函数对象是定义了函数调用运算符的类对象,称作class type functor。
// comparator predicate: returns true if a < b, false otherwise
struct IntComparator
{
bool operator()(const int &a, const int &b) const
{
return a < b;
}
};
https://github.com/wangcy6/weekly/tree/master/reading-notes/object-model
目录
类内存布局
image.png
几个问题
class NewCalcuClient
{
private:
std::function<int(int, int)> m_function;
public:
NewCalcuClient(std::function<int(int, int)> function) : m_function(function){}
int calculate(int x, int y)
{
return m_function(x, y);
}
};
测试代码:
Minus minus;
CalcuClient client(&minus);
Plus plus;
CalcuClient client2(&plus);
int r = client.calculate(7, 4);
int r2 = client2.calculate(7, 4);
//bind+function
NewCalcuClient newclient(boost::bind(&Minus::calculate, &minus, _1, _2));
NewCalcuClient newclient2(boost::bind(&Plus::calculate, &plus, _1, _2));
int r3 = newclient.calculate(7, 4);
int r4 = newclient2.calculate(7, 4);
bind+function相比虚函数的实现在性能上并不占优,