作者:深圳教育在线 来源:www.szedu.net 更新日期:2009-8-12
有时候,我们会用宏为类生成一些函数,类名是这些函数名字的一部分,例如以下代码中,DECLARE_CLASSNAME_FUNC 定义了函数CLSfunc。另一方面,我们可能希望能够通过模板函数来调用以上函数。问题是在模板中,函数名被T代替了,在编译时不可能根据T的不同而确定调用有不同名字的函数。这里,可以引入函数重载的概念,特别要注意的是,重载函数中要用二级指针,原因是这样能够在编译时刻即知道子类有没有重载该函数(一级指针可以在类层次结构中由下向上隐式转换,故需要用二级指针) view plaincopy to clipboardprint? #define DECLARE_CLASSNAME_FUNC(CLS) \ void CLS##func(){}//declare function CLSfunc #define CALL_CLASSNAME_FUNC(CLS) \ CLS##func();//call function CLSfunc #define DECLARE_OVERRIDE_FUNC(CLS) \ void overridefunc(CLS**){}// CLS** is preferred rather than CLS* class Base{ public: DECLARE_CLASSNAME_FUNC(Base); DECLARE_OVERRIDE_FUNC(Base); }; class Derive : public Base{ public: DECLARE_CLASSNAME_FUNC(Derive); DECLARE_OVERRIDE_FUNC(Derive); }; template<class T> void templatefunc() { T* pT = NULL; pT->overridefunc(&pT); } int _tmain(int argc, _TCHAR* argv[]) { templatefunc<Derive>();// will call Derive::Derivefunc internally return 0; }
|