Skip to main content

Class and function template with syntax

Short answer

A function template defines a generic function: template<class T> ret func(T args){...}. The compiler deduces T from calls. A class template defines a generic class: template<class T> class Class { ... }; objects like Class<int> obj; specify T. Outside member definitions require template<class T> and Class<T>:: scope.

What do you mean by Class Template and Function Template? Write down the syntax of Class Template and Function Template.

Function template

A function template is a single generic function definition that works for many data types. The compiler generates the actual function for each type used (template instantiation).

template <class T>            // or: template <typename T>
return_type function_name(T arg1, T arg2) {
    // body using T
}

Example:

template <class T>
T maxOf(T a, T b) { return (a > b) ? a : b; }
// maxOf(3, 7) -> int version;  maxOf(2.5, 1.5) -> double version

Class template

A class template is a generic class whose data members and member functions can use a type parameter. The class is instantiated for a specific type when an object is declared.

template <class T>
class ClassName {
    T data;                       // member of generic type
public:
    ClassName(T d);
    T getData();
};

// member function defined outside the class
template <class T>
ClassName<T>::ClassName(T d) { data = d; }

template <class T>
T ClassName<T>::getData() { return data; }

Object creation: ClassName<int> a(5); ClassName<float> b(2.5f);

Function templateClass template
Generic functionGeneric class
Type deduced from argumentsType given explicitly in <>
Called like a normal functionUsed to declare objects

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 9 questions →