tags:

views:

332

answers:

1

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  A: 

Please see http://stackoverflow.com/questions/738933/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();
}
MP24
But extern templates are not implemented currently in MSVC. How can this be done otherwise.I looked at the thread. How can i deal with it though?
UberJumper
I think it works, at least if Microsoft Extensions are enabled. You'll additionally have to combine it with `declspec` dllimports/exports, probably.Remember that the pointer definition has to be in the CPP file.
MP24
@uberjumper: This is the solution to instantiate a template class and export/import this instance to/from a DLL. It has nothing to do with extern templates. Still... the code of the template class should be fully visible at compilation time.
Cătălin Pitiș