单实例模版类
来源:互联网 发布:java直销系统源码 编辑:程序博客网 时间:2024/05/21 23:42
一个最简单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;
///////// 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;
- 单实例模版类
- 一个函数模版和类模版实例
- c++ Template模版类,实例
- c++ 函数模版,类模版,实例化,具体化,模版作参数,模版的友元
- 函数模版与类模版简单实例--学习笔记
- 类模版的实例化instantiation
- [c++ primer plus]c++ 函数模版,类模版,实例化,具体化,模版作参数,模版的友元
- [c++ primer plus]c++ 函数模版,类模版,实例化,具体化,模版作参数,模版的友元
- 单实例类
- 单实例对象类
- SIngleton单实例类
- makefile 单文件夹模版
- MFC 单文档模版SDI中 取得当前应用程序实例句柄
- \t\tMFC 单文档模版SDI中 取得当前应用程序实例句柄
- C++工具箱(一)——单件模版类
- Template模版实例(C++)
- c++模版应用实例
- c++模版编程实例
- 公司职位英文简写
- TCP拥塞控制算法内核实现剖析(九)
- OSPF的ROUTER-ID选取规则
- servlet程序开发===永远的helloworld
- vs下编译Qt Demos与Examples
- 单实例模版类
- 类似百度输入框自动联想功能遇到的问题:Opera浏览器不支持拼音输入法时的keyup事件
- shell script
- Creating symbolic link 'bin/libtalloc.so.2': Operation not supported
- 2-SAT
- 初级程序员考试大纲
- sql server学习笔录5(T-SQL 日期处理总结)
- yii framework 报错: Cannot modify header information - headers already sent by
- Nature:蛔虫病治疗新视野