Tuesday, April 17, 2007

Template Function in CPP file

Is it possible to do that ?? i mean writing template functions in c++ file ??? , Yeah it is possible.
Suppose we have class , its name is CSimple.


so the header may look like this
///CSimple.h
template <typename T>
class CSimple
{
     T anything;
public :
     void SimpleTest();
};
So we need to put the SimpleTest function outside the class. If it is the same header file , it is fairly easy to do
like this
template <typename T>
void CSimple<T> :: SimpleTest()
{
}
thats all. No pains. But it is in the c++ file you will get linker error (At least in VS ).
So to do that we can define .cpp file as this

 // CSimple.cpp
#include
"CSimple.h"
template <typename T>
void CSimple<T> :: SimpleTest()
{


}
template CSimple<int>;
so in your main if are creating a creating an object of template class like CSimple<int> it will compile perfectly.


If u are creating objects of other types you have to give that class information in the cpp file. Like if you want to instantiate the template class with float you need to give template CSimple<float> in the cpp files. So sometimes it may not be possible to modify cpp files. So it is better to create a new cpp files and include the original cpp in that , also we can define our template class in that too. Like shown below


 /// CComplex.cpp
#include "CSimple.cpp"
template  CSimple <float>


This will work definitely .

Sunday, April 1, 2007

STL vector and list Difference

If you are using STL fist time , you can see that these are the classes for holding a gropup of things.
You need to include #include <vector> and #include <list> for using these classes, also specify they are in std namespace . This can be done by using namespace std;

We all know these stuff. So what is the difference between vector and list ? When i compared the names first time , i can't see any difference, vector is something which has magnitude and direction in maths ( just joking) and list is our linked list ( doubly or single ).  No it is not like that , Actually the vector class only allows to insert in the back side or front side ( No addition in between ). But list allows.  list has function like insert() , using we can insert to any position. You may think then why we need vector? Ofcourse we need because , list costs perfomance degrade for allowing us to insertion in between the two ends. So IF you don't want to insert in between the front and last end , use vector. This can be speed up your performance.

One other difference is in vector each elements can be accesses using [] . But in list it won't possible.


These are the Key differece. In implementation wise vector is like dynamic array (When i say dynamic array u may think that "Is that same linked list ???"  , Not exactly ,the STL doc says that they have done some perfomance tuning for vector) , and list is the same linke list