Consider the following header file:
// Foo.h
class Foo {
public:
template
void read(T& value);
};
I
If you intend to use your class only in a single module (i.e. you won't export it) you can use boost/mpl/for_each. The template function defined this way (using mpl/for_each) won't be exported (even if you declare __declspec(export) before class name or function signature):
// Foo.cpp
#include
#include
template
void read(T& value)
{
...
}
using types = boost::mpl::vector;
//template instantiation
struct call_read {
template
void operator()(T)
{
T t; //You should make sure that T can be created this way
((Foo*)nullptr)->read(t); //this line tells to compiler with templates it should instantiate
}
};
void instantiate()
{
boost::mpl::for_each(call_read());
}
If you need export/import you structure and template methods there is the solution using boost/preprocessor
// Foo.h
#ifdef
# define API __declspec(dllexport)
#else
# define API __declspec(dllimport)
#endif
class API Foo {
public:
template void read(T& value);
};
// Foo.cpp
#include
#include
#include
template
void read(T& value)
{
...
}
//using this macro you can define both boost::mpl structure AND instantiate explicitly your template function
#define VARIANT_LIST (std::wstring)(long)(int)
using types = boost::mpl::vector;
//Here we should use our API macro
#define EXPLICIT_INSTANTIATION(r, d, __type__) \
template API void Foo::read<__type__>(__type__&);
BOOST_PP_SEQ_FOR_EACH(EXPLICIT_INSTANTIATION, _, VARIANT_LIST)
If you don't need this extra functionality the first solution is much cleaner I guess