将错误与嵌套模板链接

时间:2012-03-12 14:45:22

标签: c++ templates linker singleton nested

我有一个类系统,它继承自一个本身继承自Singleton的模板。

问题是静态成员* ms_Singleton *无法在我的类的专业版中正确链接。 我收到了以下错误:

  

错误LNK2001:未解析的外部符号“protected:static class MyBase * Singleton> :: ms_Singleton”

我的代码是:

template <typename T> 
class Singleton
{
protected:
    static T* ms_Singleton;

public:
    Singleton( void )
    {
        ms_Singleton = static_cast< T* >( this );
    }
    static void init(void){};
    static T& getSingleton( void )
    {   assert( ms_Singleton );  return ( *ms_Singleton ); }
};



template <class T>
class MyBase : public Singleton< MyBase<T> >
{
    public:
        MyBase()
        {
        }
};


/*template <class T>
MyBase<T>* Singleton< MyBase<T> >::ms_Singleton = 0;*/

class MySpecialized : public MyBase<MySpecialized >
{
    public:
        MySpecialized()
        {
        }
};

template <>
MySpecialized* Singleton<MySpecialized>::ms_Singleton = 0; 

int main()
{
    MySpecialized t;
}

1 个答案:

答案 0 :(得分:1)

只需更改

template <class T>
Base<T>* Singleton< Base<T> >::ms_Singleton = 0;

template <class T>
T* Singleton<T>::ms_Singleton = 0;

检查http://ideone.com/7B0Da