Write a C++ program to illustrate template class.
AIM:
Write
a C++ program to illustrate template class.
THEORY:
Template is simple and yet very powerful tool in C++. The
simple idea is to pass data type as a parameter so that we don’t need to write
same code for different data types. For example a software company may
need sort() for different data types. Rather than writing and maintaining the
multiple codes, we can write one sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second
keyword can always be replaced by keyword ‘class’.
Templates are expended at compiler time. This is like
macros. The difference is, compiler does type checking before template
expansion. The idea is simple, source code contains only function/class, but
compiled code may contain multiple copies of same function/class.
SOURCE
CODE:
#include<iostream>
using namespace std;
template <class T>
class data{
public:
data(T
c){
cout<<"\n"<<"c=
"<<"\n size in bites"<<sizeof (c);}
};
int main(){
data<char>h('A');
data<int>i(100);
data<float>f(3.12);
}
Labels: oop through c++ lab
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home