Skip to main content

Need of template; function template overloading

Short answer

Templates eliminate redundant overloads for same logic with different types, providing reusable, type-safe code. Function template overloading occurs with multiple templates differing in parameter count or a non-template function. The compiler chooses exact non-template first, then exact template instantiation. Example: maxOf(a,b) (two args) and maxOf(a,b,c) (three args), plus a specialized maxOf for const char* using strcmp to compare strings properly.

Explain why do we need template. Explain the function template overloading with suitable example.

Why we need templates

Many algorithms (swap, find largest, sort, stack, queue) are the same for every data type. Without templates we would have to:

  • write many overloaded functions or classes that differ only in type, which wastes effort and is hard to maintain; or
  • use macros or void*, which are not type safe.

Templates (generic programming) let us write the logic once with a type parameter, and the compiler generates code for each required type. They give reusability, type safety, shorter code and easier maintenance. The standard library containers (vector, list) are built with templates.

Function template overloading

A function template can be overloaded in two ways:

  1. By another template with a different number or types of parameters.
  2. By an ordinary (non-template) function with the same name.

The compiler picks the function by this order:

  1. An exact-match non-template function.
  2. A template that can be instantiated with an exact match.
  3. Otherwise, a function needing conversion (non-template only).
#include <iostream>
#include <cstring>
using namespace std;

template <class T>                 // template 1: two values
T maxOf(T a, T b) { return (a > b) ? a : b; }

template <class T>                 // template 2: three values (overload)
T maxOf(T a, T b, T c) { return maxOf(maxOf(a, b), c); }

const char* maxOf(const char* a, const char* b) {   // ordinary overload
    return (strcmp(a, b) > 0) ? a : b;
}

int main() {
    cout << maxOf(3, 8) << endl;            // template 1, int  -> 8
    cout << maxOf(2.5, 1.5, 9.1) << endl;   // template 2, double -> 9.1
    cout << maxOf("apple", "mango") << endl;// ordinary function -> mango
    return 0;
}

Without the ordinary overload, comparing two C-strings with the template would compare their addresses, not their text; so overloading a template with a specific function handles special cases.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 9 questions →