GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Monday, December 27, 2010

C++ Template Function

Templeate function used for flexibility of the type. So you can do programming like in scripting language. See this code:

templace
myType getMin( myType a, myType b){   
   if(a
        return a;
   }else{
        return b;
   }
}

The you call it by:
int x = 2;
int y = 3;
int c = getMin(x,y);
cout << c << endl;
output>> 2

You can use this function for long data type:
long x = 456789;
long y = 456788;
int c = getMin(x,y);
cout << c << endl;
output>> 456788

More example:
template
Lol addTwo(Lol x){
    Lol r = x + 2;
    return r;
}

then call it by
cout << addTwo(2) << endl;
output>> 5
       
For using two kind of different data type, use
template
A addTwo(A a, B b){
     A r = a+b;
    return r;
}

then call it by:
int x = 4;
long y = 45;
cout << addTwo(x,y) << endl;
output>> 49
          
Share/Bookmark

1 comment: