Archived

This topic is now archived and is closed to further replies.

billybob

coercing templates to work with Dlls

Recommended Posts

billybob    134
I have two main problems with templates, one is STL templates. ie
warning C4251: needs to have dll-interface to be used by clients of class 
some of these are typedefs, ones that are used fairly often. the other is templates of my own. the most basic example is a singleton base class, others include a refcounted smart pointer (uses internal ref count of the object). I was thinking for my own, since the template implementations are all in the header file, does it even matter? If all the code in the header is going to be copy n'' pasted at the top of source files using it, why does the dll interface matter? how do I export STL templates, and how do I handle my own? any help or tips would be great

Share this post


Link to post
Share on other sites
SiCrane    11839
About 85% of the time (as long as you use the DLL version of the runtime library for both the DLL and the executable) this warning doesn''t matter. That''s the good news.

The bad news is that chances are your singleton class is one of the situations that won''t work. In this case you''ll probably have a static variable reference issue. Code from the DLL will try to reference a static variable in the DLL and code from the executable will try to reference a static variable in the executable. This is likely bad mojo. (For example causing two copies of a singleton to exist. Bad mojo indeed.)

Let''s say I wanted to use a std::vector<int> in a class in my DLL. Then, in my header, I should set up some code that looks like:

#ifdef DLLVEC_EXPORTS
#define DLLVEC_API __declspec(dllexport)
#define EXPIMP_TEMPLATE
#else
#define DLLVEC_API __declspec(dllimport)
#define EXPIMP_TEMPLATE extern
#endif

EXPIMP_TEMPLATE template class DLLVEC_API std::vector<int>;

The #ifdef stuff is for if I''m using the header in the DLL or an outside product that uses the DLL.

Share this post


Link to post
Share on other sites
billybob    134
ok, thanks a bunch for the template stuff. about the class statics, I was thinking, why can''t you put the MYDLL_API on the static itself, why wouldn''t that make it work? I know it doesn''t let you if the class already has the import/export stuff on it, but why not?

Share this post


Link to post
Share on other sites
SiCrane    11839
Static variable references aren''t the only thing that could screw up. It''s just the easiest thing to explain when it does screw up, and fairly easy to diagnose.

Share this post


Link to post
Share on other sites