- Asked 4/10
- 2073 Shrawan · 2+2 marks
- 2072 Chaitra · 5 marks
- 2069 Chaitra · 5 marks
- 2068 Baisakh · 2+2 marks
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 template | Class template |
|---|---|
| Generic function | Generic class |
| Type deduced from arguments | Type given explicitly in <> |
| Called like a normal function | Used to declare objects |
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Class template with multiple template types · Object Oriented Programming, chapter 9
- Class template with suitable example · Object Oriented Programming, chapter 9
- Default arguments in class template · Object Oriented Programming, chapter 9
- Array class template with max, min, sort · Object Oriented Programming, chapter 9
- Importance of function template · Object Oriented Programming, chapter 9 · asked 2×
- Need of template; function template overloading · Object Oriented Programming, chapter 9
- Top-down view for F = xz + yz' · Embedded System, chapter 8
- Create classes from design class diagrams · Object Oriented Analysis and Design, chapter 4 · asked 2×
- Class C pool for 32, 65, 10, 21, 9 · Computer Networks and Security, chapter 4 · asked 2×
- Class C pool for 10, 12, 8, 14 · Computer Networks and Security, chapter 4 · asked 2×