Template instantiations in a CPP file

You can put explicit template instantiations in a separate CPP file and it will compile and link successfully as long as you instantiate all of the types you’re going to use. Note that all you need to do to instantiate a template is to declare it with the explicit types:

Header file:

class C
{
public:
    template <typename T>
    T method(const T& t1, const T& t2);
};

CPP file:

#include <string>

#include <instantiation.h>

template <typename T>
T C::method(const T& t1, const T& t2)
{
    return t1 + t2;
}

// These are the explicit instantiations
template int C::method<int>(const int&, const int&);
template std::string C::method<std::string>(const std::string&, const std::string&);

Program file

#include <iostream>
#include <string>

#include <instantiation.h>

int main()
{
    C c;
    std::string str1 = "Hello ";
    std::string str2 = "World!";
    std::cout << c.method(str1, str2) << "\n";
    std::cout << c.method(1, 2) << "\n";
}
Hello World!
3