I want to export template functions from DLL. I know I can use template specialization method as following.
func.hpp
/*declare*/
template<typename T>
DLL_EXPORTS T func(T para);
/*specialization*/
template<>
DLL_EXPORTS int func<int>(int para);
func.cpp
template<>
DLL_EXPORTS int func<int>(int para)
{return para;}
If I use template specialization. I should rewrite the func code for every type. It’s not a good solution. But this is the only way I can found from the C++ Primer.
I found another way occasionally from someone else’s codes, as following.
func.hpp
/*declare*/
template<typename T>
DLL_EXPORTS T func(T para);
func.cpp
template<typename T>
DLL_EXPORTS T func (T para)
{return para;}
/*Instantiation*/
template
DLL_EXPORTS int func<int>(int);
He use template DLL_EXPORTS int func<int>(int) to instantiate the template. you can’t add <> after the keyword template. This way also works on class template.
My question: I can’t find the way in the book. So I’m afraid that it’ll not work sometimes. Is it supported by the C++ standard?
Yes, it called explicit instantiation See 14.7.2 of the C++11 standard (sorry I have no C++03 nearby).
You may instantiate in your translation unit as much as you wish instances of your template w/ any types you want, and this code will be placed into your DLL. And everything else just wouldn’t.