I am trying to create and use a template function. This template function will be visible to multiple different source files. I only want to use this function with certain template parameters. I also want this to compile once. Therefore, I think I should explicitly instantiate the template in the instances I want it available in the source file where it is defined.
This is effectively what I have so far:
mytemplate.h
template <typename T>
void foo(T* thing, std::string other);
mytemplate.cpp
template <typename T>
void foo(T* thing, std::string other)
{
doStuff(thing)
}
template void foo<MyType1>(MyType1* thing, std::string other);
template void foo<MyType2>(MyType2* thing, std::string other);
main1.cpp
#include mytemplate.h
...
foo<MyType1>(thing1, other1);
foo<MyType2>(thing2, other2);
...
main2.cpp
#include mytemplate.h
...
foo<MyType1>(thing, other);
...
My questions are:
- Will this compile the explicit template instances only once?
- Will the template still be able to be implicitly instantiated elsewhere in the code with different template parameters?
Note that the codebase I am working on is using C++ 14.