I've got a template class in which I must initialize a member variable (to null) like so:
template <typename T>
T * Singleton<T>::m_pInstance = NULL;
I put this at the end of the class declaration (in the header file). I realise that the correct place for this is in the cpp file, but the class is small and only contains inline functions.
This works correctly in regular programs where the header file is part of the solution. But now I want to add the class to a DLL, and export it from the DLL.
Where can I put the __declspec(dllexport) in this initialization, so that I can export this variable from a DLL?
The documentation I've read says that the correct way is as follows:
// ENGINEPART_API is defined as __declspec(dllexport)
template <typename T> ENGINEPART_API
T * Singleton<T>::m_pInstance = NULL;
The DLL builds fine, but when I attempt to import the class into my program, I get:
1>singleton.h(52): error C2720: 'Singleton<T>::m_pInstance' : '__declspec(dllimport)' storage-class specifier illegal on members
Update
Superman tells me that I cannot export a template from a DLL. Well, I can export classes from a DLL that use that template, so that's why the template is in the DLL. I need a way to initialize this member variable (which is static).
The class declaration looks like this:
template <typename T>
class ENGINEPART_API Singleton
{
private:
static T *m_pInstance;
// ... inline functions
};
I can export classes from the DLL that use the template:
class ENGINEPART_API blah : public Singleton <blah>
{...};
You cannot export templates. An instance of the class is created only when the class is actually used and at that moment the compiler needs access to the entire source of the class template. The C++ standard talks about an export keyword that can be used to export class templates, but AFAIK there is only one compiler that implements this. So the best you can do is to have the entire template class definition in a header file.