#include <iostream>
#include <typeinfo>
void Foo ()
{
Std::cout << "foo () called" << Std::endl;
}
typedef void FooT (); FooT is a function type,
The same type as that of function foo ()
int main ()
{
Foo (); Direct call
Print types of foo and FooT
Std::cout << "Types of foo:" << typeid (foo). Name ()
<< ' \ n ';
Std::cout << "Types of FooT:" << typeid (FooT). Name ()
<< ' \ n ';
foot* PF = foo; implicit conversion (decay)
PF (); Indirect call through pointer
(*PF) (); Equivalent to PF ()
Print type of PF
Std::cout << "Types of PF:" << typeid (PF). Name ()
<< ' \ n ';
foot& RF = foo; No implicit conversion
RF (); Indirect call through reference
Print type of RF
Std::cout << "Types of RF:" << typeid (RF). Name ()
<< ' \ n ';
}
//==========================================================
#include <iostream>
Class for function objects, that return constant value
Class Constantintfunctor {
Private
int value; Value to return "function call"
Public
Constructor:initialize value to return
Constantintfunctor (int c): value (c) {
}
' Function call '
int operator () () const {
return value;
}
};
Client function that uses the function object
void Client (Constantintfunctor const& CIF)
{
Std::cout << "Calling back functor yields" << CIF () << ' \ n ';
}
int main ()
{
Constantintfunctor Seven (7);
Constantintfunctor Fortytwo (42);
Client (seven);
Client (Fortytwo);
}
//===========================================================
/* The following code example is taken from the book
* "C + + templates-the Complete Guide"
* by David Vandevoorde and Nicolai M. Josuttis, Addison-wesley, 2002
*
* (C) Copyright David Vandevoorde and Nicolai M. Josuttis 2002.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software are provided "as is" without express or implied
* Warranty, and with no claim as to their suitability for any purpose.
*/
#include <vector>
#include <iostream>
#include <cstdlib>
Wrapper for function pointers to function objects
Template<int (*FP) () >
Class Functionreturningintwrapper {
Public
int operator () () {
return FP ();
}
};
Example function to wrap
int Random_int ()
{
return Std::rand (); Call Standard C function
}
Client that uses function object type as template parameter
Template <typename fo>
void Initialize (std::vector<int>& coll)
{
Fo fo; Create function Object
for (Std::vector<int>::size_type i = 0; I<coll.size (); ++i) {
Coll[i] = FO (); Call function for function object
}
}
int main ()
{
Create vector with ten elements
Std::vector<int> V (10);
(re) initialize values with wrapped function
initialize<functionreturningintwrapper<random_int> > (v);
Output elements
for (Std::vector<int>::size_type i = 0; I<v.size (); ++i) {
Std::cout << "coll[" << I << "]:" << v[i] << Std::endl;
}
}
Template Learning Practice three functor