zoukankan      html  css  js  c++  java
  • C++模板类中使用静态成员变量(例如Singleton模式)

    一个最简单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;
  • 相关阅读:
    Mybatis学习(2)原始dao开发和使用mapper接口代理开发
    Mybatis学习(1)
    Leetcode | Merge Intervals
    GDB打印STL容器内容
    LeetCode | Max Points on a Line
    最长不减子序列【转】
    LeetCode | Evaluate Reverse Polish Notation
    LeetCode | Word Ladder II
    LeetCode | Valid Number
    LeetCode | Set Matrix Zeroes
  • 原文地址:https://www.cnblogs.com/lidabo/p/3277699.html
Copyright © 2011-2022 走看看