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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

// Template function to find the maximum of two values
template <typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    int intMax = max(10, 20); // Calls max<int>(10, 20)
    double doubleMax = max(3.14, 2.71); // Calls max<double>(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.
Ad-hoc polymorphism is also known as overloading.
Coercion is also known as (implicit or explicit) casting.
Remember that templates allow you to write generic code that works with various types, making C++ a powerful language for parametric polymorphism!
Topic archived. No new replies allowed.