Working with templates
Template is very powerful and simple tool in C++. They are called to be the foundation of generic programming that has writing codes which are independent of any particular type.A template is a formula or a blueprint to create a generic a function or a generic class. There arelibrary containers such as algorithms and iterators. Each container has single definition like vector. You can define as many vectors as you want. The algorithms are examples of generic programming which have developed to use template concept. The idea behind the template is to pass data types in form of parameters which eliminates the need of writing same code for different data types. Templates are like macros that are expended at compilation time but in templates, complier actually checks the type before template expansion. C++ has introduced two new keywords in order to support templates and they are 'typename' and 'template'. 'typename' can always be replaced by 'class' keyword. The idea behind template is to use same class or function multiple times.
This feature of C++ programming language allows classes and functions to operate by using generic types. These templates are of great utility in assisting programmers specially while working with operator overloading and multiple inheritance. The standard library of C++ provides various useful functions of connected templates within a framework. Parameterized modules provided by CLU are the major inspirations for C++.
Template Types
There are two types of Templates:
- Function Template
- Class Template
Function Template
Function templates are special kind of functions which helps in operating with generic types. These templates allows programmers to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.
Template parameters can be used to achieve this in C++. A template parameter can be used to pass values to the function just like a regular function parameter. They can also be used to pass type in a function.
For declaring a function template, use the following code:
template<class identifier>function_declaration;
template <typename identifier>function_declaration;
In the above prototypes, we have defined two templates, one by using the keyword class and another by using the keyword typename. Both expressions defined above has the same meaning and will behave in a same way.
Example to create a template function:
template<class myfirstType>
myfirstTypeGetMax (myfirstType a, myfirstType b)
{
return (a>b?a:b);
}
In the above example, a template function with its template parameter myfirstTypehas created. Another template function GetMaxwill return greater of two parameters.
Example of Function template:
// function template
#include <iostream>
usingnamespacestd;
template<class X>
X GetMax (X a, X b) {
X result;
result = (a>b)? a : b;
return (result);
}
int main () {
int i=4, j=6, k;
long l=10, m=4, n;
S=GetMax<int>(i,j);
T=GetMax<long>(l,m);
cout<< S <<endl;
cout<< T <<endl;
return 0;
}
The output of the above code will be:
6
10
Function Template with multiple arguments
These templates allow us to pass more than one datatype to templates as arguments.
#include<iostream>
using namespace std;
template<class T, class U>
class A {
T x;
#include<iostream>
using namespace std;
template<class T, class U>
class A {
T x;
U y;
Public:
A() { cout<<"Constructor Called"<<endl; }
};
int main() {
A<char, char> a;
A<int, double> b;
return 0;
}
The Output of the code will be:
Construction Called
Construction Called
Overloading of function template
Function template can be overloaded either by a function template or by non-template function. It supports overloading mechanism. When overloaded function template is called, the compiler deduces template argument and check for its explicitly declared arguments. It instantiates a function template, if it is successful and then adds this specialization to candidate functions that are used in overloaded resolution. After this addition, the complier proceeds with further overload resolution. It will choose the best function from the set of candidate functions.
#include <iostream>
using namespace std;
template<class M> void s(M x, M y) { cout<< "Template" <<endl; }
void s(int w, int z) { cout<< "Non-template" <<endl; }
int main() {
s( 1 , 2 );
s('a', 'b');
s( 1 , 'b');
}
The output of the above code will be:
Non-template
Template
Non-template
The function call s(1, 2)will match the argument types of both the non-template function and template functions. As non-template take precedence over template function, the non-template function is going to be called in overload resolution.
The function call s('a', 'b') will match the argument types of the template function only when the template function is called.
When will call s(1, 'b')Argument deduction will fail for the function call and the compiler will not generate any template function specialization and also there will be no overload resolution takes place. Only non-template function can resolve this function call by using conversion from char to int for the function argument 'b'.
When program contains overloaded functions, the complier uses the following rules to choose an appropriate function:
- It will search for an accurate match of functions, if it found, it will be invoked.
- It will search for a template function by the help of which a function can be invoked with an accurate match that should be generated. Again it is invoked, if it found.
- It will attempt a normal overloading declaration for all functions.
- An error will be reported, if there is no case match is found.
// overloaded functions
#include <iostream>
usingnamespacestd;
int sum (int x, int y)
{
returnx+y;
}
double sum (double x, double y)
{
returnx+y;
}
int main ()
{
cout<< sum (20,20) <<'\n';
cout<< sum (2.0,1.5) <<'\n';
return 0;
}
The output of the above code will be:
40
3.5
In the above code, sum is overloaded with different parameter types, but the body is exactly the same.
The function sum used above could be overloaded for many other different types, and it will make sense for all of them by having the same body. For such cases such, C++ provides the ability to define various functions whichhave generic types and they are known as function templates. A function template can be defined by following the same syntax as a regular function, except the condition that it should be preceded by the template keyword and followed by a series of template parameters that are enclosed in angle-brackets <>.
template<template-parameters> function-declaration
The template parameters contain a series of parameters that are separated by commas. These parameters can be described as generic template types by simply specifying either thetypename or class that is inturn followed by an identifier. This identifier, later on can be used in the function declaration process as a regular type.
template<classSomeType>
SomeType sum (SomeType x, SomeType y)
{
returnx+y;
}
As you see it will make no difference whether the generic type is specified withtypename keyword or class keywordkeyword class in the list of template argument list.
The above code clearly depicts that declaring SomeType (which is generic type within the template with required parameters enclosed in angle-brackets) are allowingSomeType to be used anywhere during function declaration in the function definition, just like any other type; they can be used as return type, as the type for parameters or while declaring new variables of this type. In all such cases, theyrepresent a generic type which will goingto determine on the moment the template is instantiated.
Instantiating a template can be described as applying the template so as to create a functionby using appropriate values or types for its template parameters. This can be done by calling the function template by using same syntax like calling a regular function.
name<template-arguments> (function-arguments)
For example, the sum function template defined above can be called with:
x = sum<int>(20,20);
The function sum<int> is the possible instantiations used in the function template sum. In the above code, template argument is uses int by calling the function. In that case, the compiler will going to instantiatesautomatically a version of sum where each occurrence of SomeType will be replaced by int, as if it was defined as:
int sum (int X, int y)
{
returnx+y;
}
The output of the above code will be:
40
Class Template
A class template is a template used to provide specification while generating classes based on parameters. Class templates are useful in implementing containers. A class template is initiated by passing set of types to it in the form of template arguments. The standard Library of C++ contains various class templates, such as vector can be adopted from Standard Template Library. Class Template use template parameters as types that can have members.
To define class template, use the below code:
template<class T>
classmyfirstpair {
T values [2];
public:
myfirstpair (T first, T second)
{
values[0]=first; values[1]=second;
}
};
The above code will serve to store two elements which are of any valid type. In order to declare an object of this class for storing two integer values, use intwith values 110 and 35.
Then we should write the below code:
myfirstpair<int>myobject (110, 35);
Example of a Class Template:
// class templates
#include <iostream>
usingnamespacestd;
template<class X>
classmyfirstpair {
X a, b;
public:
myfirstpair (X first, X second)
{a=first; b=second;}
X getmax ();
};
template<class X>
X myfirstpair<X>::getmax ()
{
X retval;
retval = a>b? a : b;
returnretval;
}
int main () {
myfirstpair<int>myobject (100, 75);
cout<<myobject.getmax();
return 0;
}
The output of the above code will be:
100
Member Function Templates
Function template can be defined outside any template class. However, functions are the member functions of class in C++. While creating class template that goes with the function template, programmer doesn't have to create function template explicitly because template will contain function definitions. Noninlined or inlined member functions that are declared with class template are function template implicitly. When a programmer declares template class, it will implicitly generate template functions that are actually defined in the class template for each function.
Template member function can be defined in three ways:
- Inlined member function in class template itself.
- It can be defined at file scope by using temporary arguments.
- It can be defined explicitly at file scope used to instantiate the template class for each type.
Member function templates are used in order to instantiate those functions which are not explicitly generated. When you have both an explicit definition and a member function template in that case the explicit definition is used.
template<class H> class Key
{
Key(); // default constructor
Key( H ); // constructor taking H by value
Key<H>(H ); // error, <H> implicit within class template
};
The declaration Key<H>(H) will show an error because any constructor does not use the template argument. This class template can be corrected by removing the offending line; a programmer can define this function template for the class template's constructor as shown below.
// Constructor contained in function template:
template<class H>
Key<H>::Key(int) { /* ... */ }
// valid, constructor template argument assumed template<class H>
Key<H>::Key<H>(int) { /* ... */ }
/* error, constructor template argument <H> implicit
in class template argument */
argument) refers to the class, while Key(int) { /* ... */ } refers to the member function.
Some fundamental drawbacks of using templates are as follows:
- Some old compilers do not support for templates. So, it may decrease code portability while using the template.
- There exist many compilers who lacks in clear instructions while detecting a template for definition error. This might increase the efforts in developing templates.
- As the compiler will generate additional code for template type, a larger executables will come up when there is indiscriminate use of templates that can lead to code bloat.
- By its nature, a template exposes its implementation, when use in large systems, it can lead to longer build times.
- It is difficult to debug the code is developed using template. It will difficult for a debugger to locate the code during runtime.
How we help you? - C++ Assignment Help 24x7 - Tutor Service
We offer Working with C++ assignment help, C++ assignment writing help, assessments writing service, Working with Templates tutors support, step by step solutions to Working with Templates problems, Working with Templates answers, C++ Tutorial assignment experts help online. Our C++ Tutorial assignment help service is most popular and browsed all over the world for each grade level.
There are key services in C++ which are listed below:-
- C++ Tutor service help
- Assignment Help
- Homework Help
- C++ Assessments Writing Service
- Solutions to problems
- C++ Tutorial papers writing and editing
- C++ Expert's support 24x7
- Online tutoring
Why choose us - The first thing come in your mind that why choose us why not others what is special and different about us in comparison to other site. As we told you our team of expert, they are best in their field and we are always live to help you in your assignment which makes it special.
Key features of services are listed below:
- Confidentiality of student private information
- 100% unique and original solutions
- Step by step explanations of problems
- Minimum 4 minutes turnaround time - fast and reliable service
- Secure payment options
- On time delivery
- Unlimited clarification till you are done
- Guaranteed satisfaction
- Affordable price to cover maximum number of students in service
- Easy and powerful interface to track your order