让我们有以下代码:
template <typename T> struct X
{ X() { }
};
struct __declspec(dllexport) A
{ struct __declspec(dllexport) AB
{ int i;
};
typedef X <AB> XAB;
//template struct __declspec(dllexport) X <AB>; // error C2252: an explicit instantiation of a template can only occur at namespace scope
static XAB x; // warning C4251: 'A::x' : struct 'X<T>' needs to have dll-interface to be used by clients of struct 'A'
static X <AB> x2; // warning C4251: 'A::x2' : struct 'X<T>' needs to have dll-interface to be used by clients of struct 'A'
X <AB> x3; // warning C4251: 'A::x3' : struct 'X<T>' needs to have dll-interface to be used by clients of struct 'A'
};
template struct __declspec(dllexport) X <A::AB>; // Has no effect
所以:
- 我有一个要导出到 DLL 的类。
- 这个类也有一个要导出到 DLL 的子类。
- 有类型的变量 ('x...')
template <subclass>
。 - 成员变量也需要 dll 导出。
- 所以我需要
template <subclass>
在使用这种类型之前显式地实例化。 - 但这是不可能的,因为实例化只能在全局范围内进行。
但是在全局范围内,子类(还)没有定义。
template <class::subclass>
类体之后的实例化没有效果。
那么如何正确处理这个问题,避免任何警告和错误呢?
顺便说一句:类中模板的实例化在 VS2008 中运行良好。
先感谢您。
葡聚糖