### Can you give me an example of parametric polymorphism

Hi,

I need a few examples of parametric polymorphism please.

Regards,
Juan Dent
Last edited on
Here's what CoPilot has to say:

Certainly! In C++, parametric polymorphism is achieved using templates. Let’s delve into the details:

Parametric Polymorphism (Compile-Time Polymorphism):
Parametric polymorphism provides a way to execute the same code for any type.
In C++, it is implemented via templates.
One of the simplest examples is a generic max function that finds the maximum of two of its arguments.
Here’s how you can define a template function for finding the maximum:
 ``1234567891011121314151617`` ``````#include // Template function to find the maximum of two values template T max(T a, T b) { return (a > b) ? a : b; } int main() { int intMax = max(10, 20); // Calls max(10, 20) double doubleMax = max(3.14, 2.71); // Calls max(3.14, 2.71) std::cout << "Max integer: " << intMax << std::endl; std::cout << "Max double: " << doubleMax << std::endl; return 0; }``````

In this example, the max function works for both integers and doubles because it’s parametrically polymorphic.
Other Names for Polymorphisms in C++:
Subtype polymorphism is also known as runtime polymorphism.
Parametric polymorphism is also known as compile-time polymorphism.