Junior — Middle
Explain the concept of static polymorphism and its use in programming.
sobes.tech AI
Answer from AI
Static polymorphism is the ability of a programming language to select the implementation of a function or method at compile time, not at runtime.
In C++, static polymorphism is achieved through templates and function overloading. It allows creating generic code that is compiled for specific types, providing high performance without the overhead of virtual calls.
Example with templates:
template<typename T>
T add(T a, T b) {
return a + b;
}
int main() {
int x = add(2, 3); // for int
double y = add(2.5, 3.5); // for double
}
Static polymorphism is useful when performance and type safety are important, such as in STL libraries or generic algorithm implementations.