![](/img/trans.png)
[英]How to use a dllexport-ed class which is derived from an explicitly instantiated template in a dll without warnings?
[英]Importing explicitly instantiated template class from dll
作为一个 dll 新手,我不得不向全能的 SO 询问一些事情。
假设我像这样显式实例化模板 class :
template class __declspec(dllexport) B<int>;
如何再次使用导入此模板 class?
我已经尝试在我想使用 B 的 my.cpp 文件中添加下面的代码
template class __declspec(dllimport) B<int>;
当你完全实例化一个模板时——你就有了一个完整的类型。 它与任何其他类型没有什么不同。 您需要包含用于B
的 header 并且还需要使用lib
文件进行编译时链接或动态加载 dll 以链接到定义。
您是否阅读过这篇文章: http://support.microsoft.com/kb/168958 ?
这是我测试的内容的简要摘要(并且有效):
创建一个虚拟 DLL 项目
template_export_test
文件: template_export_test.h
#ifndef EXP_STL
#define EXP_STL
#endif
#ifdef EXP_STL
# define DECLSPECIFIER __declspec(dllexport)
# define EXPIMP_TEMPLATE
#else
# define DECLSPECIFIER __declspec(dllimport)
# define EXPIMP_TEMPLATE extern
#endif
EXPIMP_TEMPLATE template class DECLSPECIFIER CdllTest<int>;
文件: template_export_test.cpp
template<class T>
CdllTest<T>::CdllTest(T t)
: _t(t)
{
std::cout << _t << ": init\n";
}
创建测试应用程序
driver
的 Win32 控制台应用程序template_export_test.lib
的路径template_export_test.lib
template_export_test.h
#include "c:\Documents and Settings\...\template_export_test.h"
using namespace std;
int main(int argc, char** argv) {
CdllTest<int> c(12);
}
看起来,即使模板的显式实例化,也可能出现导致运行时错误的问题。 看看这篇关于 C4251 的有趣文章(尤其是“结论”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.