vs编写C++单例模板报错

打算写一个C++单例的模板类,编写完代码后,报一个链接错误。
操作系统:windows
编辑器:vs2017

代码

singleton.h

#include 
#include 

class TestSingleton;
template <class T>
class Singleton
{
private:
    Singleton() {};
    virtual ~Singleton() {}

public:
    static T* GetInstance();

private:
    static T* instance;
    //std::mutex mutex;
};

singleton.cpp

#include "Singleton.h"

template 
T * Singleton::instance = nullptr;

template 
T* Singleton::GetInstance()
{
    if (instance == nullptr)
    {
        instance = new T;
    }
    return instance;
}

main.cpp

#include 
#include "Singleton.h"

class TestSingleton
{
public:
    TestSingleton()
    {
    }
    ~TestSingleton()
    {
    }

    static void test()
    {
        std::cout << "TestSingleton::test" << std::endl;
    }

private:

};

int main()
{
    std::cout << "Hello World!\n";
    //单例测试代码
    /*TestSingleton sig;
    sig.test();*/
    //TestSingleton::test();
    Singleton::GetInstance()->test();
}
运行结果及详细报错内容

vs编译报以下错误

img

曾用过继承的方式编写调用singleton的代码,编译依然报错。
希望能够编译通过,请指教!

看起来你在尝试使用 C++ 单例模板时遇到了一个链接错误。这是因为你在 singleton.cpp 中声明了单例模板的静态变量和成员函数,但是在 singleton.h 中没有定义它们。

为了解决这个问题,你可以将 singleton.cpp 中的所有定义都移到 singleton.h 中,然后在 main.cpp 中包含 singleton.h,这样就可以正常编译和链接了。

具体来说,你可以将 singleton.h 的内容修改为:

#include <mutex>
#include <iostream>

template <class T>
class Singleton
{
private:
    Singleton() {};
    virtual ~Singleton() {}
public:
    static T* GetInstance();
private:
    static T* instance;
    //std::mutex mutex;
};

template <class T>
T * Singleton<T>::instance = nullptr;

template <class T>
T* Singleton<T>::GetInstance()
{
    if (instance == nullptr)
    {
        instance = new T;
    }
    return instance;
}

并将 singleton.cpp 删除。

需要注意的是,在 C++ 中使用单例模板的时候,通常需要使用实例化来生成单例的代码。你可以在 main.cpp 中添加以下代码来实例化单例模板:

template class Singleton<TestSingleton>;

这样就可以在 main 函数中使用 Singleton::GetInstance() 获取单例的实例了。