zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++模板类中使用静态成员变量(例如Singleton模式)

C++模板静态模式变量 成员 类中 Singleton
2023-09-27 14:28:16 时间
一个最简单Singleton的例子:///////// Test.h /////////template class CTest{private:_T n;static CTest* m_pInstance;   // Notice: static member variable in templa...
一个最简单Singleton的例子:

///////// Test.h /////////
template class _T
class CTest
{
private:
_T n;
static CTest _T * m_pInstance;   // Notice: static member variable in template class
private:
CTest() { n = 0; }
~CTest() { }
public:
static CTest _T * Instance()
{
if (!m_pInstance)
{
m_pInstance = new CTest _T
}
return m_pInstance;
}
void Set(const _T value)    { n = value;   }
};

///////// Test.cpp /////////
#include "Test.h"
CTest int * CTest int ::m_pInstance = NULL;

编译时提示: too few template-parameter-lists,真是莫名其妙的错误提示。

在网上找了半天,终于有点眉目了。似乎是应模板使用是编译器做的是Lazy Evaluation,就是说只有当某个模板类(或者模板类中的某个函数)需要实例化时才实例化。也就是说上面这个例子中,编译器在编译到Test.cpp里面的那一句定义语句的时候,发现m_pInstance没有办法在整个类实例化之前分配空间。

解决方法也很简单,在定义静态成员变量的那个前面加上“template ”即可。如下:

///////// Test.cpp /////////
#include "Test.h"
template
CTest int * CTest int ::m_pInstance = NULL;