Handling template specialization with separate implementation files can be tricky, but it's doable with the right approach. Let's walk through the process step by step.
First, declare both the primary template and its specializations in the header file:
// MyTemplate.h
#pragma once
template <typename T>
class MyTemplate {
public:
void foo();
};
// Declare specialization
template <>
class MyTemplate<int> {
public:
void foo();
};
Next, implement both the primary template and specializations in a separate .cpp file:
// MyTemplate.cpp
#include "MyTemplate.h"
#include <iostream>
template <typename T>
void MyTemplate<T>::foo() {
std::cout << "General template\n";
}
// Implement specialization
void MyTemplate<int>::foo() {
std::cout << "Specialized for int\n";
}
// Explicit instantiation
template class MyTemplate<double>;
Note the explicit instantiation at the end. This is crucial for making the template available to other translation units.
Now you can use your template in other files:
// main.cpp
#include "MyTemplate.h"
int main() {
MyTemplate<double> d;
d.foo(); // Outputs: "General template"
MyTemplate<int> i;
i.foo(); // Outputs: "Specialized for int"
}
General template
Specialized for int
Remember, while this approach works, it's often simpler to keep template definitions in header files, especially for smaller projects. Only move to separate implementation files if you have a specific need, such as reducing compilation times in large projects.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to separate class templates into declarations and definitions while avoiding common linker errors