跨平台模板的写法

来源:互联网 发布:淘宝连击抽奖技巧 编辑:程序博客网 时间:2024/05/01 21:32

(若转载,请注明原出处与作者,作者:Witton)

        由于工作的原因,自己写的代码,需要跨平台运行(windows与Linux),但是由于VC编译器与gcc/g++编译器的差别,有的代码,在VC下面编译OK,在Linux下却未必编译得过,下面就是一个典型的例子:
请先看一下下面的一段代码是否有问题:

#include <iostream>using namespace std;template <typename T>class CT{public: static void StaticInit() {   pInstance = new T;   assert(pInstance); } static void StaticDestroy() {   delete pInstance; } static T* Instance() {   assert(pInstance);   return pInstance; };protected: static T* pInstance; CT( void ) { } virtual ~CT( void ) {  }};class CTestClass : public CT<CTestClass>{private: CTestClass();  friend class CT;};CTestClass * CT<CTestClass>::pInstance = NULL;

上面这段代码,在VC环境下编译是完全没有问题的;但是在Linux下编译就会有问题:

在friend class CT这一行会报错:
template argument required for `class CT'
friend declaration does not name a class or function
在最后一行代码处会报错:too few template-parameter-lists
为了让所写的代码既能在Windows下编译通过,也能在Linux下编译通过,就需要作如下修正:

将friend class CT改成friend class CT<CTestClass>
在最后一行的前一行加上template<>  

原创粉丝点击