How do I export templated classes from a dll without explicit specification?

天大地大妈咪最大 提交于 2019-11-29 09:23:43

Since the code for templates is usually in headers, you don't need to export the functions at all. That is, the library that is using the dll can instantiate the template.

This is the only way to give users the freedom to use any type with the template, but in a sense it's working against the way dlls are supposed to work.

Are you looking into exporting an instantiation of a template class through a dll? A class along the lines:

typedef std::vector<int> IntVec;

There is some discussion how to do this on: http://support.microsoft.com/kb/168958

Another approach is to explicitly exporting each function you are interested in through a wrapper class working against this template instance. Then you won't clutter the dll with more symbols than you are actually interested in using.

When the compiler finds an instantiation of a template class, like MyTemplate<int>, then it generates the code for the template specialization.
For this reason, all the template code must be placed in an header file and included where you want to use it.
If you want to 'export' your template class, just place your code in an header file and include it where it's needed.

In your export control file.

#ifdef XXXX_BUILD
    #define XXXX_EXPORT __declspec(dllexport)
    #define XXXX_EXTERN
#else
    #define XXXX_EXPORT __declspec(dllimport)
    #define XXXX_EXTERN extern
#endif

where XXXX_BUILD is a symbol defined in your project.

To get your class exported.

XXXX_EXTERN template class XXXX_EXPORT YourClass<double>;

Where double is the type you want to instantiate the class with.

https://support.microsoft.com/en-us/help/168958/how-to-export-an-instantiation-of-a-standard-template-library-stl-clas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!