DLL和完全专业的模板类 [英] DLL and fully-specialized template class

查看:65
本文介绍了DLL和完全专业的模板类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境:Visual Studio 9,C ++,无托管扩展.

Environment: Visual Studio 9, C++ without managed extensions.

我有一个第三方库,可以导出MyClass.h中定义的完全专业的模板类MyClass<42>.它被编译为辅助加载程序.lib和.dll文件. .lib文件包含此专业的编译代码和必要的符号. MyClass.h看起来像这样:

I've got a third-party library which exports a fully-specialized template class MyClass<42> defined in MyClass.h. It gets compiled into a helper loader .lib and a .dll file. The .lib file contains compiled code for this specialization, and necessary symbols. The MyClass.h looks like this:

template<UInt D>
class MyClass {
public:
    MyClass() {...};
    virtual ~MyClass() {};
}

现在,我想使用这个库.如果将MyClass.h包含在Client.cpp中,然后对其进行编译,则将在Client.obj文件中获得这些符号的第二个副本.我可以通过将该专业的所有成员定义为外部"来摆脱这些符号.我的Client.cpp看起来像这样:

Now I'd like to use this library. If I include the MyClass.h in a Client.cpp and then compile it, I'll get second copy of these symbols in the Client.obj file. I can get rid of these symbols by defining all the member of that specialization as "extern". My Client.cpp looks like this:

#include <ThirdParty/MyClass.h>

extern template class MyClass<42>;
extern template MyClass<42>::MyClass<42>();
extern template MyClass<42>::~MyClass<42>();

void MyFunction(MyClass<42>& obj) {...}

问题是我无法以这种方式摆脱虚拟析构函数.对于虚拟析构函数,我得到一个几乎标准的LNK2005错误:

The problem is that I cannot get rid of the virtual destructor this way. For the virtual destructor I get an almost standard LNK2005 error:

ThirdPartyd.lib(ThirdPartyd.dll) : error LNK2005:
    "public: virtual __thiscall MyClass<42>::~MyClass<42>(void)"
    (??1?$MyClass@$01@@@UAE@XZ) already defined in Client.obj

我该怎么办?

推荐答案

对于虚拟方法,似乎有必要同时将它们定义为extern__declspec(dllimport):

It seems that for virtual methods it is necessary to define them as both extern and __declspec(dllimport) at the same time:

extern template __declspec(dllimport) MyClass<42>::~MyClass<42>();

这使我的链接程序很高兴可以正确地链接我的代码.

This made my linker happy enough to link my code properly.

如果有些专家描述了为什么会这样,或者至少指向一些解释这种情况的文章,我会感到很高兴.

I would be very glad if some expert described why is so, or at least pointed to some article explaining this case.

这篇关于DLL和完全专业的模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆