C++ Templates
C++ Templates
Templates let you write a function or class that works with different data types.
They help avoid repeating code and make programs more flexible.
C++ Function Templates
You can create a function template by using the template
keyword:
Syntax
template <typename T> return_type function_name(T parameter) { // code }
T
is a placeholder for a data type (likeint
,float
, etc.).- You can use any name instead of
T
, butT
is common.
Example
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << add<int>(5, 3) << "\n";
cout << add<double>(2.5, 1.5) << "\n";
return 0;
}
Try it Yourself »
In the example above, add<int>(5, 3)
tells the compiler to use int
for T
, while add<double>(2.5, 1.5)
tells it to use double
.
C++ Class Templates
You can also use templates to make classes that work with any data type:
Syntax
template <typename T> class ClassName { // members and methods using T };
The example below defines a template class Box
that can store and display a value of any data type, and then creates one box for an int
and one for a string
:
Example
template <typename T>
class Box {
public:
T value;
Box(T v) {
value = v;
}
void show() {
cout << "Value: " << value << "\n";
}
};
int main() {
Box<int> intBox(50);
Box<string> strBox("Hello");
intBox.show();
strBox.show();
return 0;
}
Try it Yourself »
And this example defines a template class Pair
that stores two values of different types and displays them, then creates one pair for a person's name and age, and another for an ID and score:
Example
template <typename T1, typename T2>
class Pair {
public:
T1 first;
T2 second;
Pair(T1
a, T2 b) {
first = a;
second = b;
}
void display()
{
cout << "First: " << first << ", Second:
" << second << "\n";
}
};
int main() {
Pair<string, int>
person("John", 30);
Pair<int, double> score(51, 9.5);
person.display();
score.display();
return 0;
}
Try it Yourself »
Why Use Templates?
Templates let you:
- Avoid repeating the same logic for different types
- Write cleaner, reusable code
- Support generic programming
Note: Templates must be defined in the same file where they are used (usually in the .h
file).