Template

Problématique

On pourrait s'amuser à créer plusieurs fois la même fonction pour différents types :

int Min(int x, int y)
{
    return x<y ? x : y;
}
std::string Min(std::string x, std::string y)
{
    return x<y ? x : y;
}

Solution

Templates offer compile-time parametric polymorphism. The following function works for all types with < implemented.

template <class T>
T Min(T x, T y)
{
    return x<y ? x : y;
}

Pareil pour les classes


template <class T>
class Stack
{
    // just use T for a type
}