Templates are a compelling feature of C++. They pass various data types as parameters, so we don’t have to write the same code for different data types.
For example, consider the case in which we need to find the maximum value between two different data types. Rather than writing the same code for two different data types, we can simply write one maximum function and pass the data type as the parameter. This will make it easier for us to maintain the code and increase its reusability.
The following code will do just that:
#include <iostream>using namespace std;template <typename U>// Funtion to find the max valueU maxVal (U firstVal, U secondVal){return (firstVal > secondVal)? firstVal: secondVal;}int main() {//Calling function with integral data typecout << maxVal<int>(2, 3) << endl;//Calling same function with double data typecout << maxVal<double>(2.3, 3.2) << endl;return 0;}
For the compiler, it will be something like what is shown below:
Currently, the code written above can accept all data types, even char
and string
. What if we only wanted to add integral or floating-point types in the function header? This is where concepts come into the picture. With concepts, we can easily express such requirements on the template parameters.
Concepts are an extension of templates. They are used to perform compile-time validation of template arguments through boolean predicates.
In the following example, we will only accept the integrals and floating-point types in the function header with the help of concepts, and return the added value:
#include <iostream>#include <concepts>template <typename T>concept Number = std::integral<T> || std::floating_point<T>;template <typename T>requires Number<T>// Funtion to add two valuesauto add(T a, T b) {return a+b;}int main() {//Calling function with integral data typestd::cout<<add(5,42)<< endl;//Calling same function with double data typestd::cout<<add(3.3,42.6)<< endl;return 0;}
One thing to keep in mind here is that it will not work for the following:
std::cout<<add(3,42.6)<<'\n';
Or for this:
std::cout<<add(42.6,3)<<'\n';
For this, we need to carry out a template specialization.
Free Resources