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

简介: 一个最简单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;
目录
相关文章
|
4天前
|
存储 编译器 C语言
c++的学习之路:5、类和对象(1)
c++的学习之路:5、类和对象(1)
19 0
|
18天前
|
存储 C++ 容器
C++STL(标准模板库)处理学习应用案例
【4月更文挑战第8天】使用C++ STL,通过`std:vector`存储整数数组 `{5, 3, 1, 4, 2}`,然后利用`std::sort`进行排序,输出排序后序列:`std:vector<int> numbers; numbers = {5, 3, 1, 4, 2}; std:sort(numbers.begin(), numbers.end()); for (int number : numbers) { std::cout << number << " "; }`
19 2
|
4天前
|
C++
c++的学习之路:7、类和对象(3)
c++的学习之路:7、类和对象(3)
19 0
|
3天前
|
设计模式 Java C++
【C++高阶(八)】单例模式&特殊类的设计
【C++高阶(八)】单例模式&特殊类的设计
|
3天前
|
编译器 C++
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
|
7天前
|
存储 安全 C语言
【C++】string类
【C++】string类
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
9天前
|
编译器 C++
标准库中的string类(上)——“C++”
标准库中的string类(上)——“C++”
|
9天前
|
编译器 C++
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”
|
9天前
|
存储 编译器 C++
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(上)——“C++”
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(上)——“C++”