Which C++ feature allows a function to work with different data types without writing separate functions for each type?

template <typename T>
T maximum(T a, T b)
{
    return (a > b) ? a : b;
}
                        

Options

  • A. Function template
  • B. Namespace
  • C. Destructor
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

A. Function template

Detailed Explanation

Answer: (A) Function template

A function template allows the same function logic to be used with different data types.

In the example, T is a template type parameter.

The compiler can generate an appropriate version of the function when it is used with types such as int, float or double.

This reduces the need to write separate functions containing the same logic for different data types.