1 - Templates in C++ With Examples
1 - Templates in C++ With Examples
Special functions that can interact with generic types are known as function templates. As a
result, we can develop a function template whose functionality can be applied to multiple types
or classes without having to duplicate the full code for each kind.
This may be done in C++ by using template parameters. Similar to how standard function
parameters may be used to send values to a function, template parameters allow you to pass
types to a function as well. A template parameter is a specific form of the parameter that can be
used to pass a type as an argument. These parameters can be used by these function templates
just like any other ordinary type.
So, this blog is here to help you out in understanding the details of templates in c++, how they
work, templates specialization, templates library and many more. Read on to know more!
C++ template is also known as generic functions or classes which is a very powerful feature in
C++. A keyword “template” in c++ is used for the template’s syntax and angled bracket in a
parameter (t), which defines the data type variable.
1
What is the function template in C++?
A function template in c++ is a single function template that works with multiple data types
simultaneously, but a standard function works only with one set of data types.
C++ Function Template Syntax
#include<iostream.h>
using namespace std;
template<classX>//can replace 'class" keyword by "typename" keyword
X func( Xa,Xb)
{
return a;
}
int main()
count<<func(15,8),,endl;//func(int,int);
count,,func('p','q'),,endl;//func(char,char);
count<<func(7.5,9.2),,endl;//func(double,double)
return();
}
Output
15
p
7.5
2
Defining a Class Member Outside the Class Template
You’ve seen how a member function is defined within a class template. Now, alternatively, it is
also possible for the template member function to be defined independently of the declaration of
its class template.
The compiler will use the template arguments that you used, in this case, to create the class
template when you call a member function of a class template specialization. The following
illustration exemplifies this:
Example:
#include<iostream>
using namespace std;
template<class A> class B {
public:
A operator+(A);
};
int main() {
B<char> ob1;
B<int> ob2;
cout<< ob1 +'p' << endl;
cout<< ob2 + 10;
return 0;
}
Output:
P
10
A definition of the overloaded addition operator is given outside of class A. It is equal to the
statement ob1.operator+(‘p’) rather than ob1+ “p”. “ob2 + 10” is similar to “ob2.operator+” (10).
Simple Calculator Using Class Templates
We can make a simple Calculator performing the four basic arithmetic operations in C++ using a
class template. The template of the class will consist of two variables whose values are passed at
the time of object creation. The constructor of this class takes two arguments of generic
datatypes. Further, you will see, this Calculator class template consists of five main functions –
show(), addition(), subtraction(), multiplication(), and division(). The show() function is
responsible for calling the rest of the four generic functions. Moving ahead, we have created two
instances from the template of Calculator class and performed the basic calculations using its
class functions.
3
Example:
template <class Temp>
class Calculator
{
private:
Temp n1, n2;
public:
Calculator(Temp num1, Temp num2)
{
n1 = num1;
n2 = num2;
}
void show()
{
cout << "Addition is: " << n1 << "+" << n2 << "=" << addition() << endl;
cout << "Subtraction is: " <<n1 << "-" << n2 << "=" << subtraction() << endl;
cout << "Product is: " << n1 << "*" << n2 << "=" << multiplication() << endl;
cout << "Division is: " << n1 << "/" << n2 << "=" << division() << endl;
}
int main()
{
Calculator<int> Calc1(25, 12);
Calculator<float> Calc2(13.6, 5.9);
cout << endl << "Float results for 13.6 and 5.9:" << endl;
Calc2.show();
return 0;
}
Output
4
C++ Class Templates With Multiple Parameters
It is possible to provide more than one type when generating templates. A class template can
have many generic data types. They are listed in a comma-delimited format as shown in the
following example.
Example:
#include<iostream>
using namespace std;
// Driver function
int main()
{
// instantiation
Sample <int, char> ob1 (24, 'A');
5
// instantiation
Sample<int, float> ob2(22.56, 34.9);
return 0;
}
Output:
As seen in the above cited example, we can use more than one parameter for a template in C++.
Here, the template Temp takes two parameters, both of the Sample class type, separated by a
comma. Moreover, the constructor of the Sample class takes two arguments of generic datatype.
When we create objects, the types of arguments are specified in angular brackets (< >). In case of
multiple parameters, the datatypes are also separated by commas. The constructor is called at the
time when objects are created, and template arguments receive values.
1 template<class Ttype>
2 class class_name
3 {
4 //class body;
}
5
Here Type is a placeholder type name, which will be specified when a class instantiated.
Source Code:
#include<iostream.h>
using namespace std;
6
template <class C>
class A{
private;
C,a,b;
public:
A(Cx,Cy){
a=x;
b=y;
}
void show()
}
count<<"The Addition of"<<a<<"and"<<b<<"is"<<add()<<endl;
}
C add(){
C c=a+b;
return c;
}
};
int main(){
Aaddint(8,6);
Aaddfloat(3.5,2.6);
Aaaddouble(2.156,5.234);
Aaddint.show();
cout<<endl;
adddouble.show();
count<<endl;
return 0;
}
Output
This is used when multiple functions do similar This is used when functions do identical
operations. operations.
Function overloading can take varying numbers of Templates cannot take varying numbers of
arguments. arguments.
7
Templates avoid some common errors found in code that make heavy use of function-like
macros.
Both templates and macros are expanded at compile time.
They are a good way of making generalisations for APIs.
8
T max(T a, T b)
{
return a > b ? a : b ;
}
int main()
{
cout << "max(80, 95) = " << max(10, 15) << endl ;
cout << "max('a', 'z') = " << max('k', 's') << endl ;
cout << "max(11.1, 18.2) = " << max(11.1, 18.2) << endl ;
cout << "max(\"Ahil\", \"Riya\") = " << max("Ahil", "Riya") << endl ;
return 0 ;
}
Output
max(80, 95) = 95
max('a', 'z') = z
max(11.1, 18.2) = 18.2
max("Ahil", "Riya") = Riya
Class Specialization
Class specialization example:
Source Code:
#include <iostream>
using namespace std;
template <>
class Test <int>
{
public:
Test()
{
// Initialization of data members
cout << "Specialized template \n";
}
9
};
int main()
{
Test<int> a;
Test<char> b;
Test<float> c;
return 0;
}
Output
Specialized template
General template
General template
How does template specialisation work?
When we write any template-based function or class, the compiler creates a copy of that
function/class whenever the compiler sees that being used for a new data type or a new set of
data types(in case of multiple template arguments).
If a specialised version is present, the compiler first checks with the specialised version and then
the main template. The compiler first checks with the most specialised version by matching the
passed parameter with the data type(s) specified in a specialised version.
Template Parameter
Source Code
template <std::string * temp> //pointer to object
void f()
10
{
cout << *temp << endl;
}
int main() {
s = "can assign values locally";
f<&s>();
g<s>();
cout << s << endl;
return 0;
}
Output:
If a multi-file template has editable parameters, the Hot Spot Session, which deploys when you
apply this template, will guide you through all created files where the user input is required.
Create an item template as you would manually create a single-file item template, but include
each of the files that constitute the multi-file item.
In the ‘.vstemplate’ XML file, add a ‘ProjectItem’ element for each individual file, and add a
‘TargetFileName’ attribute to this element. Set value of the TargetFileName attribute to
11
‘$fileinputname$.FileExtension’, where FileExtension is the file extension of the file that is
included in the template.
Multi-file item template example:
1
<ProjectItem TargetFileName="$fileinputname$.vb">
2 Form1.vb
3 </ProjectItem>
4 <ProjectItem TargetFileName="$fileinputname$.Designer.vb">
5 Form1.Designer.vb
6 </ProjectItem>
<ProjectItem TargetFileName="$fileinputname$.resx">
7 Form1.resx
8 </ProjectItem>
9
Select the files that need to be included in your template, right-click the selection, and
choose Send to > Compressed (zipped) folder.
The files that you have selected are compressed into a .zip file.
Copy the .zip file to the user-item template location. The directory is
‘%USERPROFILE%\Documents\Visual Studio
<Version>\Templates\ItemTemplates’ by default.
Example
12
</TemplateContent>
</VSTemplate>
Standard Template Library in C++
A standard template library in C++ is a repository of C++ template classes. These template
classes help in implementing commonly used algorithms and data structures. These template
classes can be used with any user-defined type as well as a built-in type. STL algorithms are
container-independent and thus reduce the complexity of the library. This approach implements
compile-time polymorphism over run-time polymorphism.
Different types of templates supported by C++14 are, class templates, function templates,
vardiac, and non-vardiac templates.
In general, an instrument for imposing a consistent layout, appearance, and feel across several
pages or inside content sections is a template. Any pages or regions that are based on a template
are immediately modified whenever a template is altered. This concept is applied in codes as
well, so that we can use a defined layout multiple times.
The two major categories of templates are – class templates and function templates.
13
What is a template example?
A class or a function whose layout can be used as many times as required in a code is made into
a template. For example, we can create templates for functions like sort(), minimum(),
maximum(), arrayPrint(), Fibonacci(), etc. Similarly, we can create class templates for heavy
structures, for instance, linkedList(), Queue(), Stack(), Book(), etc.
With the aid of C++ templates, you can create a group of classes or functions that can handle
various forms of data. When there is a need to duplicate the same code across many types, we
use templates. Several advantages of templates are as follows:
They increase the efficiency of the program by reducing the developing-time when used in
combination with STL
They permit type generalization.
They reduce the quantity of repetitive code you must type.
They assist in writing type-safe code.
They are assessed during compilation.
They aid in creating extremely powerful libraries
14