How do I export templated classes from a dll witho

2019-01-26 05:49发布

I have a dll that contains a templated class. Is there a way to export it without explicit specification?

4条回答
疯言疯语
2楼-- · 2019-01-26 06:01

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.

查看更多
倾城 Initia
3楼-- · 2019-01-26 06:01

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

查看更多
劫难
4楼-- · 2019-01-26 06:05

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.

查看更多
小情绪 Triste *
5楼-- · 2019-01-26 06:12

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.

查看更多
登录 后发表回答