Re: dllexport vs. template + inheritance
Imre wrote:
So, my questions are:
- Why does the compiler fully instantiate the template, if the derived
class is exported, while it instantiates only the class declaration if
it's not exported?
It can't tell whether the module using the dll is going to call them or
not, so it has to export them anyway.
- Can I safely ignore these warnings? My simple tests indicate that
yes, they can be ignored, but I'd like to see some more educated
opinions.
I'd be surprised is an explicit call to DllDerived::F actually linked
ok, but if your tests demonstrate it, I'm sure it's fine. However, the
following gives a way which should get rid of the troublesome warning.
- Is there a solution that avoids the warnings, but doesn't require
DllMoreDerived.h to include DllTemplateImpl.h?
Yes, look at my little changes below:
Here's some sample code:
// --- DllTemplate.h ---
#ifndef DllTemplate_H
#define DllTemplate_H
template <typename T>
class DllTemplate
{
public:
void F();
};
#endif
// --- DllTemplateImpl.h ---
#ifndef DllTemplateImpl_H
#define DllTemplateImpl_H
#include "DllTemplate.h"
template <typename T>
void DllTemplate<T>::F()
{
}
#endif
// --- DllDerived.h ---
#ifndef DllDerived_H
#define DllDerived_H
#include "DllTemplate.h"
//declare the existence of this explicit instantiation
//This is an MS extension, but it is being added to the standard
extern template class __declspec(dllexport) DllTemplate<int>;
class __declspec(dllexport) DllDerived:
public DllTemplate<int>
{
};
#endif
// --- DllDerivedInstantiations.cpp ---
#include "DllTemplate.h"
#include "DllTemplateImpl.h"
template class __declspec(dllexport) DllTemplate<int>;
// --- DllDerived.cpp ---
#include "stdafx.h"
#include "DllDerived.h"
#include "DllTemplateImpl.h"
//apparently export must happen where the extern isn't visible.
//This shouldn't be the case, and isn't the case in the proposed
//standard version of "extern template".
//template class __declspec(dllexport) DllTemplate<int>;
// --- DllMoreDerived.h ---
#ifndef DllMoreDerived_H
#define DllMoreDerived_H
#include "DllDerived.h"
class __declspec(dllexport) DllMoreDerived:
public DllDerived
{
};
#endif
// --- DllMoreDerived.cpp ---
#include "stdafx.h"
#include "DllMoreDerived.h"
With that change, you still need to disable warning 4231, but at least
it's obvious why you're doing it. Finally, see here:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1960.html
Tom