Write a c++ program to illustrate member function template.
AIM:
Write
a c++ program to illustrate member function template.
THEORY:
In Function Templates, a function template was defined outside of
any template class. However, functions in C++ are often member functions of a
class. If you want to create a class template and a set of function templates
to go with that class template, you do not have to create the function
templates explicitly, as long as the function definitions are contained within
the class template. Any member function (inlined or noninlined) declared within
a class template is implicitly a function template. When a template class is
declared, it implicitly generates template functions for each function defined
in the class template.
You can define template member functions three ways:
- Explicitly
at file scope for each type used to instantiate the template class.
- At file
scope with the template arguments.
- Inlined in
the class template itself.
Member function templates are used to instantiate any functions
that are not explicitly generated. If you have both a member function template
and an explicit definition, the explicit definition is used.
The template argument is not used in a constructor name. For
example:
template<class
L> class Key
{
Key(); // default constructor
Key( L ); // constructor taking L by value
Key<L>( L ); // error, <L> implicit within class
template
};
The declaration Key<L>(L) is an error because the
constructor does not use the template argument. Assuming this class template
was corrected by removing the offending line, you can define a function
template for the class template's constructor:
//
Constructor contained in function template:
template<class
L>
Key<L>::Key(int) { /* ... */ }
// valid, constructor template argument
assumed template<class L>
Key<L>::Key<L>(int) { /* ...
*/ }
/* error, constructor template argument
<L> implicit
in class template argument */
A template function name does not include the template argument.
The template argument does, however, appear in the template class name if a
member function of a template class is defined or declared outside of the class
template.
The definition:
Key<L>::Key(int)
{
/* ... */
} is valid because Key<L> (with template argument) refers to
the class, while Key(int) { /* ... */ } refers to the member function.
SOURCE CODE:
#include<iostream>
using namespace std;
template<class E>
void exchange (E&a,E&b)
{
E
temp=a;
a=b;
b=temp;
};
int main()
{
int
x=5,y=8;
float
a,b;
cin>>a>>b;
cout<<"\n
enter the values:";
cout<<"\n
before exchange"<<"\n x="<<x<<"\n
y="<<y;
exchange(x,y);
cout<<"\n
after exchange"<<"\n x="<<x<<"\n
y="<<y;
cout<<"\n
before exchange"<<"\n a="<<a<<"\n
b="<<b;
exchange(a,b);
cout<<"\n
after exchanging"<<"\n a="<<a<<"\n
b="<<b;
return
0;
}
Labels: oop through c++ lab
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home