How templates are instantiated
When a template is used with a specific type, the compiler creates a new instance of the template with the specified type. This process is known as template instantiation and can happen implicitly or explicitly:
- Implicit instantiation: This occurs when the compiler encounters a use of the template with specific types:
int main() {
std::cout << add(5, 3) << std::endl; // The compiler infers the type as int
return 0;
}
- Explicit instantiation: The programmer specifies the type explicitly:
int main() {
std::cout << add<int>(5, 3) << std::endl; // Explicitly specifies the type as int
return 0;
}