Unit V: Namespace and Function Template
C++ templates enable generic programming by allowing the definition of generic classes and
functions, thus supporting various data types with a single implementation. They are
declared using the 'template' keyword followed by template parameters, and can take the
form of either function templates or class templates. This flexibility allows algorithms to
operate on multiple data types seamlessly.
Function Templates
Function templates in C++ provide a blueprint for creating functions that handle multiple data
types without the need for code duplication. By using a generic type specified at the function
call, a single template can accommodate various data types unlike standard functions, which
are limited to a single data type set. For example, a template can be used to define an `add`
function that works with integers, floats, or doubles.
Class template
A class template provides a blueprint for creating classes that can handle various data types,
facilitating generic programming. It allows for a single class definition to manage different
types of data through a specified template syntax. An example given illustrates its application
with a template class that compares two numbers.
Overloading function template
Function templates can be overloaded, allowing multiple templates with the same name to
be created based on varying template parameters. This enables code reusability and
flexibility, as different function behaviors can be tailored to argument types. Examples in C++
illustrate adding and multiplying integers and floating-point numbers using such templates.
1. Explain Namespace with suitable programming example
A namespace in C++ is a feature used to avoid name conflicts by grouping entities like
classes, objects, and functions under a name. It helps organize code and prevents
ambiguity, especially in large projects or when using multiple libraries.
Syntax:
namespace namespace_name {
// declarations
}
To access members of a namespace, the scope resolution operator ::
is used.
Example:
#include<iostream>
using namespace std;
namespace A {
, void display() {
cout << "Inside Namespace A" << endl;
}
}
namespace B {
void display() {
cout << "Inside Namespace B" << endl;
}
}
int main() {
A::display(); // Accessing function from namespace A
B::display(); // Accessing function from namespace B
return 0;
}
Output:
Inside Namespace A
Inside Namespace B
2. Define template. Explain types of Template with suitable example.
Or
3. Explain template with its types.
A template in C++ allows writing generic and reusable code that works with different data
types. It supports generic programming, where functions or classes can operate on various
types without rewriting code.
Types of Templates:
1. Function Template
A function template is used to create a single function definition to work with different data
types.
Syntax:
template <typename T>
return_type function_name(T arg1, T arg2) {
// function body