C++ tricks, #6: Explicit template instantiation
Today we take a look at explicit template instantiations (yet another post which is a direct result of user feedback
). With explicit template instantiations, you can define a template and instantiate it in a DLL, so clients don’t even have to see the implementation of the template. All you need is a language extension (extern template) which will become part of C++0x, and is currently supported by GCC, Intel and MSVC.
The DLL
Let’s assume we have this great class:
and we want to provide our clients an instance which works with integers only. For this to work, we put the definition into a separate file (you’ll see later why), container_impl.h:
Then we include both in a file in our DLL, let’s call it container_in.cpp like this:
Now clients can already use the integer container, by including only container.h which does not contain the definitions!
More flexibility
But what if clients want to use a float container? With the current solution, they’ll get an error that the definition is not available. To get it working, the client has to include container_impl.h as well. But now, Container<int> will be instantiated twice, which leads to an error. The workaround is to define the instantiation as extern template, which means don’t generate code for this template even if the definition is available (for some reason or another, I just tried and it also works without the extern with Visual C++ 9). The finished file is:
The container_in.cpp file has to #define IN_ now. The client works like this:
That’s it!
^ Back to top
No comments
Jump to comment form | comments rss [?] | trackback uri [?]