您的位置:首页 > 编程语言 > C语言/C++

Effective C++ 条款35:为虚函数寻求替代方案

2012-02-21 15:19 459 查看
原书内容:

策略模式:通过tr1::function模板实现

如果你对模板和模板的隐式接口的用法(参见第41条)很熟悉的话,那么上述的“基于函数指针”的方案就显得十分蹩脚了。旧的方案必须使用一个函数来实现生命值计算的功能,我们考虑:能不能用其它一些东西(比如函数对象)来代替这个函数呢?为什么这个函数不能是成员函数呢?还有,为什么这个函数一定要返回一个整数值,而不能返回一个可以转型至int的类型呢?

个人测试代码如下:

调试环境:

GCC 4.5.2

如果在VS2008下,则#include <functional> 可参见http://msdn.microsoft.com/en-us/library/bb982198.aspx

#include <iostream>
#include <tr1/functional>

using namespace std;

class GameCharacter;
class GameLevel
{
public:
float health(const GameCharacter&) const
{
cout << "health calc" << endl;
return 1.1;
}
};

int defaultHealthCalc(const GameCharacter&)
{
return 0;
}

class GameCharacter
{
public:
typedef std::tr1::function<int (const GameCharacter&)> HealthCalcFunc;
explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc) : healthFunc(hcf)
{

}
int healthValue()const
{
healthFunc(* this);
return 1;
}

private:
HealthCalcFunc healthFunc;
};

int main()
{
GameLevel currentLevel;
GameCharacter gc(tr1::bind(&GameLevel::health, currentLevel, tr1::placeholders::_1));
gc.healthValue();

return 0;
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: