Saturday, May 29, 2010

c++ - create personal library using template(linux platform)

/*create own personal library in c++, using gcc compiler in linux platform.
atfirst create a source file and a header file. then create a main file to
include header file. here tem.cpp is source file and tem.h is header
file. main.cpp is main file.here tempalte is used instead of function definition. */
//template is a general case for functions for diff. datatypes as "int,float,double".
//note : - use '>' & '<' as ']' & '[' respectively.
//"tem.h"
template[class T]
T sum[T a,T b]
{
return a+b;
}

//"tem.cpp"
#include[iostream]
#include"tem.h"

//compile source file tem.cpp as "gcc -c tem.cpp"
//object file tem.o is created.

//"main.cpp"
#include[iostream]
#include"tem.h"
using namespace std;
int main()
{
cout[["sum is "[[sum(3,5)[[endl;
cout[["sum is "[[sum(3.0,5.0)[[endl;
return 0;
}

//compile it as "g++ -Wall main.cpp tem.o
//run as "./a.out" result will be
//"sum is 8"
//"sum is 8.0"

No comments:

Post a Comment