Module 46
Module 46
Intructors: Abir
Das and
Sourangshu
Bhattacharya
Module 46: Programming in C++
Objectives &
Outlines Functors: Function Objects
Function Pointers
Callback
qsort
Issues
Module 46
Intructors: Abir
Das and
Sourangshu
• Understand the Function Objects or Functor
Bhattacharya
• Study the utility of functor in design, especially in STL
Objectives &
Outlines
Function Pointers
Callback
qsort
Issues
Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Module 46
Intructors: Abir
Das and
Sourangshu
Bhattacharya
1 Function Pointers
Objectives &
Outlines
Callback
qsort
Function Pointers
Callback Issues
qsort
Issues
Functors
Basic Functor
Simple Example
2 Functors in C++
Examples from STL Basic Functor
Function Pointer
Simple Example
Examples from STL
Function Pointer
Module 46
Intructors: Abir
Das and
Sourangshu
• Points to the address of a function
Bhattacharya
◦ Ordinary C functions
Objectives & ◦ Static C++ member functions
Outlines
◦ Non-static C++ member functions
Function Pointers
Callback • Points to a function with a specific signature
qsort
Issues ◦ List of Calling Parameter Types
Functors ◦ Return-Type
Basic Functor
Simple Example ◦ Calling Convention
Examples from STL
Function Pointer
Module 46
Intructors: Abir
• Define a Function Pointer
Das and
Sourangshu
int (*pt2Function) (int, char, char);
Bhattacharya
Objectives &
• Calling Convention
Outlines int DoIt (int a, char b, char c);
Function Pointers
int DoIt (int a, char b, char c) {
Callback
printf ("DoIt\n");
qsort return a+b+c;
Issues }
Functors • Assign Address to a Function Pointer
Basic Functor pt2Function = &DoIt; // OR
Simple Example pt2Function = DoIt;
Examples from STL
Function Pointer • Call the Function pointed by the Function Pointer
int result = (*pt2Function) (12, ’a’, ’b’);
return a + b + c; return a + b + c;
} }
DoIt DoIt
207 207
Module 46
Intructors: Abir
• Define a Function Pointer
Das and int (A::*pt2Member)(float, char, char);
Sourangshu
Bhattacharya
• Calling Convention
Objectives &
Outlines class A {
int DoIt (float a, char b, char c) {
Function Pointers
Callback
cout << "A::DoIt" << endl; return a+b+c; }
qsort
};
Issues
Module 46
Intructors: Abir
Das and
Sourangshu
• Operations
Bhattacharya
◦ Assign an Address to a Function Pointer
Objectives & ◦ Compare two Function Pointers
Outlines
◦ Call a Function using a Function Pointer
Function Pointers
Callback ◦ Pass a Function Pointer as an Argument
qsort
Issues
◦ Return a Function Pointer
Functors
◦ Arrays of Function Pointers
Basic Functor
Simple Example
• Programming Techniques
Examples from STL
Function Pointer
◦ Replacing switch/if-statements
◦ Realizing user-defined late-binding, or
. Functions in Dynamically Loaded Libraries
. Virtual Functions
◦ Implementing callbacks
Module 46
# include < iostream >
Intructors: Abir using namespace std ;
Das and
Sourangshu // The four arithmetic operations
Bhattacharya float Plus ( float a , float b ) { return a + b ; }
float Minus ( float a , float b ) { return a - b ; }
Objectives &
Outlines float Multiply ( float a , float b ) { return a * b ; }
Function Pointers float Divide ( float a , float b ) { return a / b ; }
Callback int main () {
qsort int ch , a , b ;
Issues
cout << " Enter 0 for add , 1 for sub , 2 for mult and 3 for div : " ;
Functors
cin >> ch ;
Basic Functor
Simple Example
cout << " Enter 2 numbers : " ;
Examples from STL cin >> a >> b ;
Function Pointer switch ( ch ) {
case 0: cout << Plus (a , b ) << endl ; break ;
case 1: cout << Minus (a , b ) << endl ; break ;
case 2: cout << Multiply (a , b ) << endl ; break ;
case 3: cout << Divide (a , b ) << endl ; break ;
case 4: cout << " Enter valid choice " << endl ;
}
return 0;
}S20202: Software Engineering
C Intructors: Abir Das and Sourangshu Bhattacharya 9
Function Pointers: Replace Switch/ IF Statements
Module 46
Intructors: Abir
Das and
Sourangshu
• It is a Common C Feature
Bhattacharya
# include < iostream >
Objectives & using namespace std ;
Outlines
Module 46 void qsort(void *base, // Pointer to the first element of the array to be sorted
Intructors: Abir
Das and size_t nitems, // Number of elements in the array pointed by base
Sourangshu
Bhattacharya
size_t size, // Size in bytes of each element in the array
int (*compar)(const void *, const void*)); // Function that compares two elements
Objectives &
Outlines
int CmpFunc(const void* a, const void* b) { // Compare function for int
Function Pointers int ret = (*(const int*)a > *(const int*) b)? 1:
Callback
qsort
(*(const int*)a == *(const int*) b)? 0: -1;
Issues return ret;
Functors }
Basic Functor
Simple Example int main() {
Examples from STL
Function Pointer
int field[10];
Module 46
Intructors: Abir
Das and
Sourangshu
• No value semantics
Bhattacharya
• Weak type checking
Objectives &
Outlines
• Two function pointers having identical signature are necessarily indistinguishable
Function Pointers • No encapsulation for parameters
Callback
qsort
Issues
Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Module 46
Intructors: Abir • Smart Functions
Das and
Sourangshu ◦ Functors are functions with a state
Bhattacharya
◦ Functors encapsulate C / C++ function pointers
Objectives &
Outlines . Uses templates and
Function Pointers . Engages polymorphism
Callback
qsort • Has its own Type
Issues
Functors
◦ A class with zero or more private members to store the state and an overloaded
Basic Functor operator() to execute the function
Simple Example
Examples from STL • Usually faster than ordinary Functions
Function Pointer
Module 46
Intructors: Abir
Das and
Sourangshu
• Any class that overloads the function call operator:
Bhattacharya
◦ void operator()();
Objectives & ◦ int operator()(int, int);
Outlines
◦ double operator()(int, double);
Function Pointers
Callback ◦ ...
qsort
Issues
Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Module 46
Intructors: Abir • Consider the code below
Das and
Sourangshu int AdderFunction(int a, int b) { // A function
Bhattacharya return a + b;
Objectives &
}
Outlines
AdderFunctor aF;
int w = aF(x, y); // aF.operator()(x, y); -- Functor invocation
}
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 16
Functors: Examples from STL: Function Pointer for Functor
vector<int> V(100);
generate(V.begin(), V.end(), rand);
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 17
Functors: Examples from STL: Functor without a state
Module 46
Intructors: Abir • Sort a vector of double by magnitude
Das and
Sourangshu
Bhattacharya
◦ sort algorithm
#include <algorithm>
Objectives &
Outlines template <class RandomAccessIterator, class Compare>
Function Pointers void sort (RandomAccessIterator first, // Simple interface
Callback RandomAccessIterator last, // Difficult to use incorrectly
qsort
Issues
Compare comp); // Compare Functor
Functors . first, last: RandomAccessIterator has a range [first,last)
Basic Functor
Simple Example
. RandomAccessIterator shall point to a type for which swap is properly defined and
Examples from STL which is both move-constructible and move-assignable (C++11)
Function Pointer
. comp: Binary function that accepts two elements in the range as arguments, and
returns a value convertible to bool. The value returned indicates whether the element
passed as first argument is considered to go before the second in the specific strict weak
ordering it defines.
. The function shall not modify any of its arguments
. This can either be a function pointer or a function object
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 18
Functors: Examples from STL: Functor without a state
Functors
// Type-unsafe comparison function // Type-safe comparison functor
Basic Functor
// Intricate and error-prone with void* struct less_mag: public
Simple Example int less_mag(const void* a, const void* b) { binary_function<double, double, bool> {
Examples from STL return (fabs(*(const double*)a) < bool operator()(double x, double y)
Function Pointer fabs(*(const double*)b) ? 1: 0; { return fabs(x) < fabs(y); }
} };
Module 46
• Compute the sum of elements in a vector
Intructors: Abir
Das and
◦ for each algorithm
Sourangshu #include <algorithm>
Bhattacharya template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function fn) {
Objectives & while (first!=last) {
Outlines
fn (*first);
Function Pointers ++first;
Callback }
qsort return fn; // or, since C++11: return move(fn);
Issues
}
Functors . first, last: InputIterator has a range [first,last)
Basic Functor
. fn: Unary function that accepts an element in the range as argument
Simple Example
. This can either be a function pointer or a move constructible function object (C++11)
Examples from STL
Function Pointer
. Its return value, if any, is ignored.
◦ User-defined Functor adder with local state
struct adder: public unary_function<double, void> { adder() : sum(0) { }
double sum; // Local state
void operator()(double x) { sum += x; }
};
vector<double> V;
...
adder result = for_each(V.begin(), V.end(), adder());
cout << "The sum is " << result.sum << endl;
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 20
Module Summary
Module 46
Intructors: Abir
Das and
Sourangshu
• Introduced Function Objects or Functors
Bhattacharya
• Illustrated functors with several simple examples and examples from STL
Objectives &
Outlines
Function Pointers
Callback
qsort
Issues
Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer