Templates
Function Template
int cube(int x)
{ return x*x*x;} cube(5.5) ->fails
as works with int
Solution:
copy function and change its type. Need to do same as we expect different data
type cube, long, double etc.
Using
template, need just one copy of cube(). When function invoked, T is replaced
with specified type during call.
template
<typename T>
T cube(T
x){return x*x*x;}
cube<int>(5); cube<double>(5.5)
Datatype need not be specified, compiler can
interpret from passed argumentJ.
Side Effect: even though there is one
copy, but all occupy different space in final image.
Class Template
template
<typename T>
class Vector{
T arr[100]; int size;
public:
Vector():size(0) {}
void push(T x){ arr[size]=x; size++; }
void print() const {for(int itr=0;
itr<size; itr++) cout<<arr[itr]<<endl;}
int getsize() const{return size;}
T get(int i) const{return arr[i];}
};
int main(){
Vector<int> v; v.push(2);
v.push(3); v.print(); }
Function template
can infer data type from argument, for class template data type should be
specifically specified.
Class template with function Template
template
<typename T>
Vector<T>
operator*(const Vector<T>& a, const Vector<T>& b) {
Vector<T> ret;
for(int i=0;i<a.getsize();i++)
ret.push(a.get(i) *b.get(i) );
return ret; }
int main(){
Vector<int> v; v.push(2); v.push(3); v.push(10); v.print();
v=cube(v); v.print(); //v={8, 27, 1000}
No comments:
Post a Comment