Templates and context reasoning

It seems to be true that a concept is not really understood until it is applied.


/* Lecture 16 Programming Abstractions Templates examples of usage */ #include <cstdlib> //also exit #include <string> #include <fstream> #include <sstream> #include <iostream> #include <vector> #include <cmath> using namespace std; template <typename Type> void Swap( Type &one, Type &two) { Type tmp=one; one=two; two=tmp; } /* Doesn't work for vector type because cout can't deal with composite variable. */ template <typename T> void PrintVector(vector<T> &v) { for (unsigned int i=0;i<v.size();i++){ // cout<< v[i] <<" "; } cout<<endl; } struct coordT { double x , y ; }; void AnError(string mesg) { cerr<<mesg<<endl; exit(0); } int main() { string estr="There was no error"; float f,g; f=1.1;g=2.2; Swap(f,g); cout<<"Float "<<f<<" "<<g<<endl; int a,b; a=1;b=2; string s,t; s="123";t="456"; Swap(a,b); cout<<"Int "<<a<<" "<<b<<endl; Swap(s,t); cout<<"String "<<s<<" "<<t<<endl; vector<coordT> c; PrintVector(c); AnError(estr); return 0; }

0 comments:

Contributors

Automated Intelligence

Automated Intelligence
Auftrag der unendlichen LOL katzen