以下是c++模板实例化的一个例子,虽然ObjectList::clear()里面调用的test()函数是没有定义的,但是以下代码能够编译通过,可见ObjectList::clear()未编译;
template <typename LIST> class ObjectList : public LIST { public: size_t count(){return 0;} void clear(){test();} }; class AList { public: virtual size_t count() = 0; }; int _tmain(int argc, _TCHAR* argv[]) { AList* list = new ObjectList<AList>; list->count(); return 0; }
注:以上代码是在Windows OS上用VS编译通过的的,如果在Mac OS上用XCode编译,将会有编译错误,可见不同编译器对模板编译的时机是不一样的,VS是在使用模板时才编译。