Monday, October 8, 2007

Function Object with vector and algorithm (STL)

Hi,
I will show some more example with explanation. This functor is heavyly used in STL where
1) Many STL containers and algorithms require specifying a function to perform their operation.
2) A function that takes one parameter is called a unary function, whereas a function that takes two parameters is called a binary function.
3) STL defines three categories of functions.

1.1) Predicates- Trigger actions and always return true or false
1.2)Comparators-Order elements and always return true or false
1.3)General functions-Arbitrary operations on one or more arguments and often return a numeric value

Now we will discuss an example

#include
#include
#include
using namespace std;
class Greater_Than
{
private:
int limit;
public:
Greater_Than(int a) : limit(a) { }
bool operator()(int value)
{
return value > limit;
}
};

int main()
{
Greater_Than g(350);
vector x;
x.push_back(300);
x.push_back(460);
x.push_back(560);
x.push_back(660);
vector::iterator p;
p = find_if( x.begin(), x.end(), g );
if (p != x.end())
{
cout<< "Found element " << *p << endl;
}
}
Explanation.
The vector X is containing with 300,460,560,660.

when find_if() examines each item say x[j] in the vector x, the Greater_Than function object g will be called using operator() with the vector item

It is called like below.
// formally: g.operator()(x[j])

If it finds value greater than 350 , the very next value will be printed.
Sahu

Function Object is function pointer in C

Yes boss it is same as function pointer
Lets have an example

template "<" class T >
struct ADD
{
T operator()(T n,T n1)
{
return n+n1;
}
};

template "<" class T, class funcObj ">"
void printEval(T val,T val1,funcObj f)
{
cout <<>" ());
printEval(1.4,1.6, ADD "<" float ">" ());
return 0;
}
It is self explanatory. Do you want me to explain.? :)
I have compiled using gcc version 2.96 and redhat 7.1
It is working fine.

What is Function Object and Its Use with Example

What is Function Object in C++ ?
Answer:- It is nothing but something like Function Pointer in "C" .Regarding Function pointer and its use , how to read , how to declare all these i have discussed in my previous article.
Points:
1)It takes the place of function pointers in traditional C programming.
2)It works by overloading operator() which in turn called as Functor in c++.
3) It is used in STL.
4) STL has more generalised ,sophisticated ,robust concept of Function pointer. i.e Function Object. So function pointer is Function object we can say.
Note -: Remember(Important) Ponter to member function in c++ (.*,->*) is not exactly function pointer in C. This is something difrent I will discuss later. It is beyond scope of this discussion.
5)So any object that can be called is a function object or FUNCTOR.
6)C function pointer is just one of the example.
7)In c++ , we can call any object ,provided it is overloaded with operator().
In Summery
1.1) A Function Object, or Functor (the two terms are synonymous)
1.2) any object that can be called as if it is a function.
1.3) To accomplish this , it must defines operator().
Example.
class Greater_Than
{
private:
int limit;
public:

Greater_Than(int a) : limit(a) { }
bool operator()(int value)

{
return value > limit;
}
};

int main()
{
Greater_Than gt_five(5);
if (gt_five(7) )

{
cout<<"7 > 5" <<>
}
else
{
cout<< "7 <= 5" <<>
}
}
Explanation
See gt_five is an object of the class Greater_Than which is constructed with value 5.
Here you just notice the statement if (gt_five(7)) , we hust calling like a function.But it is an object. So here now we understood that an object of the class can be called as if it is a function, for this we just have overload the operator ().
Now when the control encounter the statement if (gt_five(7)) then control goes to operator () which return true or false.
so we get the appropiate out put.

Overloading stream insertion and extraction operators

Hi,

Now we will discuss the operator < <> > overloading. One of the advantages of using the iostream objects is that we can customize it to support our own classes.
We will just remeber few things while overloading the these operaor
Points.
1)An overloaded < <>
using namespace std;
class Base
{
public:
int a;
Base()
{
a = 100;
}
friend ostream& operator <<(ostream &os,const Base &obj);
};

ostream& operator << (ostream& os, Base & bb) {
os << bb.a;
os << '/';
return os;
}

int main()
{
Base bb1;
cout << bb1 << endl;
}

Wednesday, September 12, 2007

Example of template linking error

B.H
template '<' class t '>'
class b
{
public:
b() ;
~b() ;

} ;

// B.CPP
#include "B.H"
template '<' class t '>'
b'<' t '>'::b()
{
}
template '<' class t '>'
b'<' t>::~b()
{
}


//MAIN.CPP
#include "B.H"
void main()
{
b '<' int '>' bi ;
b '<'float '>' bf ;
}

When compiling b.cpp, the compiler has both the declarations and the definitions available. At this point the compiler does not need to generate any definitions for template classes, since there are no instantiations. When the compiler compiles main.cpp, there are two instantiations: template class
b '<'int'>' and b'<'float'>'. At this point the compiler has the declarations but no definitions!

If do g++ main.cpp ,error will come
if we write g++ main.cpp b.cpp the result is same.
Solution to this we have allready discussed, pls see in my site itselt template instatiation problem.
Regards,
sahu

Why do we need template?

It is a generic type. Something we relate to void * in C language.
It can take any type values. I mean ,It is easy to define a class like Vecror or List.But it is difficult to use the class with another type, we must replace all type names in the original file with the new type, this is a tedious and an error-prone process .
C++ provides a way to write a generic definition that works with any type --Here the answer is "templates". We use templates only to define classes that we want to work with many data types.

It can be used with classes or functions.

Boss it is also irritating if you are using GCC compiler.It's linker allways expect the template declaration and definition at a time while instatiating .If it does not see then there will be linking error some thing indefined error.



I had faced the same problem in STL some 4 years back. Actually In stl we can not have separate file for declaration and definion . It will have the linking problem.Because while instatiating , compile must see the declaration and definition at a time. . So while instatiating , by including mere .h will give the declarion , not the definition, so the linking problem.
In this case
Solution 1;
If we have 2 separate file i.e .h and .cpp , then while instatiting we should include .cpp instead of .h
Solution 2:
we have to give the definition in .h itself, and while instatiting compiler does not face any problem because it see the both declaration and definition at a time.
Note:- the gcc has implemented the vector,list all thes predefined STL in this way ,if we open any of stl header file we can see these implemetation.
This linking proble generally we don’t face in Solarice, But is a ovious problem for gcc linker

Regards,
Haramohan sahu

What is template instantiation

A C++ template is a framework for defining a set of classes or functions.
The instantiation, creates a particular class or function , by resolving the C++ template with a group of arguments that may be types or values.

Lets have an example.

#include < iostream >
#include < new >
#include < stdexcept >

using namespace std;
template < class T >
class Array
{

T *data; // pointer to heap allocated space
int size; // maximum size
public: T &operator[](int);
Array(int max);

};

template < class T >
Array::Array(int max)
{
size = max;
data = new T[size];

}//end constructor

template < class T >
T& Array::operator[](int index)
{
if (index < 0 || index > = size)
{
throw out_of_range("Array");
}
return data[index];
}//end Array

int main()
{
Array< double > test1(100);
test1[25] = 3.14;
cout< < test2(200);
Array < int > test2(200);
test2[0] = 55;
return 1;

}//end main

Now we will discuss what is instantiation ?
Here ,Array instantiates Array with type int.
This instantiation generates the following class definition:
class Array
{
int *data;
int size;
public:
int &operator[](int);
};

Like that it instatiate for float etc.
So now, we have understood what is instantiation.

Q 2) How to write the methos definition out side the class if it is a template class?

fist write the template type that the class use. Here in our case
template
then in as usual manner like reurn type then class name then method name with signature
Array::Array(int max)
{
size = max; data = new T[size];

}//end constructor



Regards,

sahu