How to Fix C++ Template Instantiation and Linker Errors
In this tutorial, you'll learn about How to Fix C++ Template Instantiation and Linker Errors. We cover key concepts, practical examples, and best practices.
C++ template instantiation errors occur when template definitions are not visible at the point of use (typically because the implementation is in a .cpp file instead of the header), or when explicit instantiation declarations do not match definitions.
Quick Fix
Wrong
// foo.h
template <typename T>
T foo(T val);
// foo.cpp
template <typename T>
T foo(T val) { return val + 1; }
// main.cpp
#include "foo.h"
int main() { return foo(42); }
undefined reference to `int foo<int>(int)'
The template definition is in foo.cpp and not visible to main.cpp.
Right
// foo.h
template <typename T>
T foo(T val) { return val + 1; }
// main.cpp
#include "foo.h"
int main() { return foo(42); }
Fix with explicit instantiation
// foo.h
template <typename T>
T foo(T val);
// foo.cpp
template <typename T>
T foo(T val) { return val + 1; }
// Explicit instantiation for needed types
template int foo<int>(int);
template double foo<double>(double);
Fix for class templates
// pair.h
template <typename T>
struct Pair {
T first, second;
Pair(T f, T s);
};
// pair.cpp - Wrong: definitions hidden
// Explicit instantiation:
template struct Pair<int>;
template struct Pair<double>;
Prevention
- Define template functions and class methods in headers, not
.cppfiles. - Use explicit instantiation in
.cppfiles when you must hide definitions. - Use
export template(C++98) or modules (C++20) for advanced separation. - Use concepts (C++20) to constrain template parameters and get better errors.
- Include all required headers in the file that uses the template.
DodaTech Tools
Doda Browser's C++ template dependency viewer shows instantiation chains across translation units. DodaZIP archives template metaprogramming code. Durga Antivirus Pro detects template instantiation depth exploits.
Common Mistakes with template instantiation
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world CPP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro