Now let us see how we can implement a function object.
class Minus
{
public:
int operator()(int a, int b) const
{
return (b - a);
}
};
{
public:
int operator()(int a, int b) const
{
return (b - a);
}
};
Now let us use the fuction object.
int testFunctionObject(int a, int b, Minus &sub )
{
return sub(a,b);
}
int main()
{
Minus funObj;
cout << testFunctionObject(10,20, funObj);
return 0;
}
cool ha...
The call to sub inside the testFunctionObject() is not a simple function call sub is an object and the statement sub(a,b) is transformed to sub.operator()(a,b) .
Now lets create a generic function object using templates.
template <class T>
class Add
{
public:
T operator()(T a,T b) const
{
return (a+b);
}
};
class Add
{
public:
T operator()(T a,T b) const
{
return (a+b);
}
};
or we can also implement in another way
class Mul
{
public:
template
};
The standard library defines several useful function objects that are used in STL algorithms for example in the sort() algorithm takes a predicate object as its third argument.... now what is predicate object , well it is a template function object that returns a bool result (greater<> / less<> used in sort to set the sorting order to ascending or descending). See the example below:
{
vector
//..fill vector
sort(vi.begin(), vi.end(), greater<int>
sort(vi.begin(), vi.end(), less
}
#include <iostream>
using namespace std;
class Minus
{
public:
int operator()(int a, int b) const
{
return (b - a);
}
};
class Add
{
public:
T operator()(T a,T b) const
{
return (a+b);
}
};
{
public:
template
};
{
double c = 0.00;
if(b!=0)
{
c = a/b;
}
return c;
}
int main()
{
int a=10,b = 30,c;
Minus sub;
c=sub(a,b);
cout << c << endl;
Add
cout << dblAdd(2.456,5.789) << endl;
Add
cout << intAdd(4,6) << endl;
Mul mul;
cout << mul(4.897,7.0) << endl;
double (*fptrDiv)(int,int);
fptrDiv = &Div;
cout << fptrDiv(20,10) << endl;
return 0;
}
No comments:
Post a Comment