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

原书内容:

策略模式:通过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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值