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
策略模式:通过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; }
相关文章推荐
- 条款35 考虑virtual函数以外的其他选择(virtual函数的替代方案)
- effective C++ 条款 35:考虑virtual函数以外的其他选择
- Effective C++ 条款35 考虑virtual函数以外的其他选择
- Effective C++ (E3 35)笔记之替代virtual函数的若干方案
- Effective C++ -----条款35:考虑virtual函数以外的其他选择
- 《Effective C++》:条款35:考虑virtual函数以外的其他选择
- 读书笔记《Effective C++》条款35:考虑virtual函数以外的其他选择
- Effective C++:条款35:考虑virtual函数以外的其他选择
- Effective C++:条款35:考虑virtual函数以外的其它选择
- effective C++ 条款 5:了解c++默认编写并调用那些函数
- Effective C++ 条款45 运用成员函数模板接受所有兼容类型
- Effective C++ 条款六 若不想使用编译器自动生成的函数,就该明确拒绝
- 条款35:考虑virtual函数以外的其他选择(Consider alternative to virtual functions)
- Item 35:考虑虚函数的其他替代设计 Effective C++笔记
- Effective C++学习5 条款05:了解C++默默编写并调用了哪些函数
- Effective C++ 条款35
- Effective C++学习笔记 条款05:了解C++默默编写并调用的哪些函数
- Effective C++:条款45:运用成员函数模板接受所有兼容类型
- 《Effective C++》学习笔记条款05了解C++默默编写并调用哪些函数
- effective C++ 条款 45:运用成员函数模板接受所有兼容类型