0% found this document useful (0 votes)
11 views

Module 46

This document discusses function pointers and functors in C++. It begins by explaining function pointers, how they point to the address of a function and can be used to call functions indirectly. Examples are given of using function pointers with ordinary C functions and C++ member functions. The rest of the document covers using function pointers to implement callbacks, replacing switch/if statements, and realizing late binding. It then introduces functors as function objects that can be used like normal functions but can encapsulate data and overloading operators. Examples of basic functors and functors from the C++ standard template library are provided.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Module 46

This document discusses function pointers and functors in C++. It begins by explaining function pointers, how they point to the address of a function and can be used to call functions indirectly. Examples are given of using function pointers with ordinary C functions and C++ member functions. The rest of the document covers using function pointers to implement callbacks, replacing switch/if statements, and realizing late binding. It then introduces functors as function objects that can be used like normal functions but can encapsulate data and overloading operators. Examples of basic functors and functors from the C++ standard template library are provided.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Module 46

Intructors: Abir
Das and
Sourangshu
Bhattacharya
Module 46: Programming in C++
Objectives &
Outlines Functors: Function Objects
Function Pointers
Callback
qsort
Issues

Functors Intructors: Abir Das and Sourangshu Bhattacharya


Basic Functor
Department of Computer Science and Engineering
Simple Example
Examples from STL
Indian Institute of Technology, Kharagpur
Function Pointer
{abir, sourangshu}@cse.iitkgp.ac.in

Slides taken from NPTEL course on Programming in Modern C++

by Prof. Partha Pratim Das

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 1


Module Objectives

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

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 2


Module Outline

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

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 3


Function Pointers

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

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 4


Function Pointers in C

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’);

• Compare Function Pointers


if (pt2Function == &DoIt) {
printf ("pointer points to DoIt\n");
}

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 5


Function Pointers in C
Direct Function Pointer Using typedef
Module 46
Intructors: Abir
Das and #include <stdio.h> #include <stdio.h>
Sourangshu
Bhattacharya
int (*pt2Function) (int, char, char); typedef int (*pt2Function) (int, char, char);
Objectives &
int DoIt (int a, char b, char c); int DoIt (int a, char b, char c);
Outlines
int main() { int main() {
Function Pointers
pt2Function = DoIt; // &DoIt pt2Function f = &DoIt; // DoIt
Callback
qsort
Issues
int result = (*pt2Function)(12, ’a’, ’b’); int result = f(12, ’a’, ’b’);
Functors
printf("%d", result); printf("%d", result);
Basic Functor
Simple Example
Examples from STL
return 0; return 0;
Function Pointer
} }
int DoIt (int a, char b, char c) { int DoIt (int a, char b, char c) {
printf ("DoIt\n"); printf ("DoIt\n");

return a + b + c; return a + b + c;
} }
DoIt DoIt
207 207

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 6


Function Reference In C++

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

Functors • Assign Address to a Function Pointer


Basic Functor
pt2Member = &A::DoIt;
Simple Example
Examples from STL
Function Pointer • Call the Function pointed by the Function Pointer
A instance1;
int result = (instance1.*pt2Member)(12, ’a’, ’b’);

• Compare Function Pointers


if (pt2Member == &A::DoIt) {
cout <<"pointer points to A::DoIt" << endl;
}
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 7
Function Pointer: Operations and Programming Techniques

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

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 8


Function Pointers: Replace Switch/ IF Statements

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 # include < iostream >


Intructors: Abir
Das and
using namespace std ;
Sourangshu // The four arithmetic operations
Bhattacharya
float Plus ( float a , float b ) { return a + b ; }
Objectives &
float Minus ( float a , float b ) { return a - b ; }
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
Issues
float (* OpPtr [4]) ( float , float ) = { Plus , Minus , Multiply , Divide };
int ch , a , b ;
Functors
Basic Functor
cout << " Enter 0 for add , 1 for sub , 2 for mult and 3 for div : " ;
Simple Example cin >> ch ;
Examples from STL cout << " Enter 2 numbers : " ;
Function Pointer
cin >> a >> b ;
cout << (* OpPtr [ ch ]) (a , b ) << endl ;
return 0;
}

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 10


Example: Callback, Function Pointers

Module 46
Intructors: Abir
Das and
Sourangshu
• It is a Common C Feature
Bhattacharya
# include < iostream >
Objectives & using namespace std ;
Outlines

Function Pointers void A () {


Callback
cout << " Hello " << endl ;
qsort
Issues
}
// Function pointer as argument
Functors
Basic Functor
void B ( void (* fptr ) () ) {
Simple Example // Calling back function that fptr points to
Examples from STL
fptr () ;
Function Pointer
}
int main () {
void (* fp ) () = A ;
B ( fp ) ; // Or simply B ( A )
return 0;
}

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 11


Function Pointers: Callback: qsort to Quick Sort

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];

for(int c = 10; c>0; c--)


field[10-c] = c;

qsort((void*) field, 10, sizeof(field[0]), CmpFunc);


}

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 12


Function Pointers: Issues

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

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 13


Functors or Function Objects

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

• Can be used to implement callbacks


• Provides the basis for Command Design Pattern

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 14


Basic Functor

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

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 15


Functors: Simple Example

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

Function Pointers class AdderFunctor {


Callback public:
qsort int operator()(int a, int b) { // A functor
Issues
return a + b;
Functors
}
Basic Functor
Simple Example
};
Examples from STL
Function Pointer
int main() {
int x = 5;
int y = 7;
int z = AdderFunction(x, y); // Function invocation

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

Module 46 • Fill a vector with random numbers


Intructors: Abir
Das and ◦ generate algorithm
Sourangshu #include <algorithm>
Bhattacharya
template <class ForwardIterator, class Generator>
Objectives &
void generate(ForwardIterator first, ForwardIterator last, Generator gen) {
Outlines while (first != last) {
*first = gen();
Function Pointers
++first;
Callback
qsort
}
Issues
}
Functors
. first, last: Iterators are defined for a range in the sequence. ”[” or ”]” means include the element and ”(” or
Basic Functor
”)” means exclude the element. ForwardIterator has a range [first,last) spanning from first element to
Simple Example
the element before the last
Examples from STL . gen: Generator function that is called with no arguments and returns some value of a type convertible to those
Function Pointer pointed by the iterators
. This can either be a function pointer or a function object
◦ Function Pointer rand as Function Object
#include <cstdlib>

// int rand (void);

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

Module 46 • Sort a vector of double by magnitude


Intructors: Abir
Das and Using qsort in C with User-defined Function less mag Using sort in C++ with User-defined Functor less mag
Sourangshu
Bhattacharya #include <stdlib.h> #include <algorithm>
// Compare Function pointer // Compare Functor
Objectives & void qsort(void *base, template <class RandomAccessIterator, class Compare>
Outlines size_t nitems, void sort (RandomAccessIterator first,
Function Pointers size_t size, RandomAccessIterator last,
Callback int (*compar)(const void *, const void*)) Compare comp);
qsort // Complicated interface. Difficult to use correctly // Simple interface. Difficult to use incorrectly
Issues

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); }
} };

double V[100]; // Capacity = 100 vector<double> V(100);


// 10 elements are filled - needs to be tracked // 10 elements are filled tracked automatically

// Difficult to call // Easy to call


qsort((void*) V, 10, sizeof(V[0]), less_mag); sort(V.begin(), V.end(), less_mag());

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 19


Functors: Examples from STL: Functor with a state

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

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 21

You might also like