Using extern templates with separate implementation files can be a powerful technique for reducing compile times in large C++ projects. Let's explore the implications and how to use this feature effectively.
Introduced in C++11, extern templates allow you to declare that a template instantiation exists somewhere else in the program, preventing the compiler from generating code for that instantiation in the current translation unit.
Here's how you might use extern templates with separate files:
// MyTemplate.h
#pragma once
template <typename T>
class MyTemplate {
public:
void foo();
};
// Declare extern template
extern template class MyTemplate<int>;
// MyTemplate.cpp
#include <iostream>
#include "MyTemplate.h"
template <typename T>
void MyTemplate<T>::foo() {
std::cout << "MyTemplate::foo()\n";
}
// Explicit instantiation
template class MyTemplate<int>;
// main.cpp
#include "MyTemplate.h"
int main() {
MyTemplate<int> obj;
obj.foo();
}
MyTemplate::foo()
MyTemplate<int>
in every translation unit that includes "MyTemplate.h".In this example, we instantiate our template for multiple sets of template arguments:
// MyTemplate.h
#pragma once
template <typename T>
class MyTemplate {
public:
void foo();
};
extern template class MyTemplate<int>;
extern template class MyTemplate<double>;
// MyTemplate.cpp
#include <iostream>
#include "MyTemplate.h"
template <typename T>
void MyTemplate<T>::foo() {
std::cout << "MyTemplate::foo() with "
<< typeid(T).name() << "\n";
}
template class MyTemplate<int>;
template class MyTemplate<double>;
Remember, while extern templates can significantly reduce compile times in large projects, they also add complexity to your code organization.
Use them judiciously, and always measure the impact on your specific project to ensure they're providing the desired benefits.
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