Avatar ·

Why C++ templates need to be defined in a header file, not in .cpp?

Hi everyone! I started learning C++ and ran into a problem that confuses me a lot. I'm trying to separate code into header files (.h) and implementation files (.cpp), as I was taught for regular classes and functions. But when I use templates, this stops working. Here's a simple example. I have a header file `math_utils.h`: ```cpp #ifndef MATH_UTILS_H #define MATH_UTILS_H template T max(T a, T b); #endif ``` And an implementation file `math_utils.cpp`: ```cpp #include "math_utils.h" template T max(T a, T b) { return (a > b) ? a : b; } ``` And `main.cpp`: ```cpp #include #include "math_utils.h" int main() { std::cout << max(3, 7) << std::endl; std::cout << max(3.5, 2.1) << std::endl; return 0; } ```