问题
So i am trying to export somethings in a project to DLL. Anyways a few of the projects use a singleton class very heavily.
template <typename T>
class DLL_IMP VA_Singleton {
protected:
VA_Singleton () {};
~VA_Singleton () {};
public:
static T *Get(){
return (static_cast<T*> (a_singleton));
}
static void Delete(){
if(a_singleton == NULL) {
delete a_singleton;
}
}
static void Create(){
a_singleton = GetInstance();
if(a_singleton == NULL){
a_singleton = new T;
}
}
private:
static T *a_singleton;
};
template <typename T> T *VA_Singleton<T>::a_singleton = NULL;
I got the export working fine, but when it comes to importing it states this:
template <typename T> T *VA_Singleton<T>::a_singleton = NULL;
Does not work with DLLImport. This is the first time ive ever really worked with DLL's in a work enviroment. Does anyone have any ideas?
回答1:
Please see Multiple Singleton Instances
You will have to ensure that your template instantiation is done in one compilation unit, and you will have to move the pointer = NULL initialization to the CPP file. In other DLLs, you'll have to use extern
templates.
Edit: If you are stuck with getting templated singletons to work over multiple DLLs, you could also define a short wrapper function that returns your singleton instance so that the template instantiation is done in one compilation unit only.
Example:
template class Singleton<T>;
__declspec(dllexport/dllimport) T& getInstanceForMyType();
// in the cpp file:
T& getInstanceForMyType()
{
return Singleton<MyType>::getInstance();
}
来源:https://stackoverflow.com/questions/1566963/singleton-in-a-dll