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

Week 08

This document provides an overview of exceptions and error handling in C. It discusses exception fundamentals like types of exceptions and exception stages. The document then covers error handling in C, including language features like return values and parameters, local goto, and signals. It also outlines the module objectives and topics to be covered.

Uploaded by

Rakesh Tripathi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Week 08

This document provides an overview of exceptions and error handling in C. It discusses exception fundamentals like types of exceptions and exception stages. The document then covers error handling in C, including language features like return values and parameters, local goto, and signals. It also outlines the module objectives and topics to be covered.

Uploaded by

Rakesh Tripathi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 143

Module M36

L
Partha Pratim
Das
Programming in Modern C++

E
Weekly Recap

Objective & Module M36: Exceptions (Error handling in C): Part 1

T
Outline

Exception

P
Fundamentals
Types of Exceptions
Exception Stages
Partha Pratim Das

N
Error Handling in
C
C Language Features Department of Computer Science and Engineering
RV & Params Indian Institute of Technology, Kharagpur
Local goto
C Standard Library
Support
[email protected]
Global Variables
Abnormal
Termination
All url’s in this module have been accessed in September, 2021 and found to be functional
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.1


Weekly Recap

Module M36

• Leveraging an innovative solution to the Salary Processing Application in C using

L
Partha Pratim
Das
function pointers, we compare C and C++ solutions to the problem

E
Weekly Recap
• The new C solution with function pointers is used to explain the mechanism for
Objective &
dynamic binding (polymorphic dispatch) based on virtual function tables

T
Outline

Exception
• Understood casting in C and C++

P
Fundamentals
Types of Exceptions
Exception Stages • Explained cast operators in C++ and discussed the evils of C-style casting

N
Error Handling in
C
• Studied const cast, static cast, reinterpret cast, and dynamic cast with
C Language Features examples
RV & Params
Local goto • Understood casting at run-time with RTTI and typeid operator
C Standard Library
Support
Global Variables
• Introduced the Semantics of Multiple Inheritance in C++
Abnormal
Termination • Discussed the Diamond Problem and solution approaches
Conditional
Termination
• Illustrated the design choice between inheritance and composition
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.2


Module Objectives

Module M36

• Understand the Error handling in C

L
Partha Pratim
Das

E
Weekly Recap

Objective &

T
Outline

Exception

P
Fundamentals
Types of Exceptions
Exception Stages

N
Error Handling in
C
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.3


Module Outline

Module M36
1 Weekly Recap

L
Partha Pratim
Das
2 Exception Fundamentals

E
Weekly Recap
Types of Exceptions
Objective &
Exception Stages

T
Outline

Exception
3 Error Handling in C

P
Fundamentals
Types of Exceptions
Exception Stages
C Language Features
Return Value & Parameters

N
Error Handling in
C Local goto
C Language Features C Standard Library Support
RV & Params
Local goto
Global Variables
C Standard Library Abnormal Termination
Support
Global Variables
Conditional Termination
Abnormal Non-Local goto
Termination
Signals
Conditional
Termination
Non-Local goto
Shortcomings
Signals
Shortcomings
4 Module Summary
Module Summary Programming in Modern C++ Partha Pratim Das M36.4
Exception Fundamentals

Module M36

L
Partha Pratim
Das

E
Weekly Recap

Objective &

T
Outline

Exception

P
Fundamentals
Types of Exceptions
Exception Stages

N
Error Handling in
C
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Exception Fundamentals
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.5


What are Exceptions?

Module M36

• Conditions that arise

L
Partha Pratim
Das
◦ Infrequently and Unexpectedly

E
Weekly Recap
◦ Generally betray a Program Error
Objective &
◦ Require a considered Programmatic Response

T
Outline

Exception ◦ Run-time Anomalies – yes, but not necessarily

P
Fundamentals
Types of Exceptions • Leading to
Exception Stages

N
Error Handling in ◦ Crippling the Program
C
C Language Features
◦ May pull the entire System down
RV & Params ◦ Defensive Technique
Local goto
C Standard Library
Support
. Crashing Exceptions verses Tangled Design and Code
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.6


Exception Causes

Module M36 • Unexpected Systems State


◦ Exhaustion of Resources

L
Partha Pratim
Das
. Low Free Store Memory

E
Weekly Recap . Low Disk Space
Objective &
◦ Pushing to a Full Stack

T
Outline

Exception • External Events

P
Fundamentals
Types of Exceptions ◦ Ĉ
Exception Stages
◦ Socket Event

N
Error Handling in
C • Logical Errors
C Language Features
RV & Params
◦ Pop from an Empty Stack
Local goto ◦ Resource Errors – like Memory Read/Write
C Standard Library
Support • Run time Errors
Global Variables
Abnormal ◦ Arithmetic Overflow / Underflow
Termination
Conditional ◦ Out of Range
Termination
Non-Local goto • Undefined Operation
Signals
Shortcomings
◦ Division by Zero
Module Summary Programming in Modern C++ Partha Pratim Das M36.7
Exception Handling?

Module M36

• Exception Handling is a mechanism that separates the detection and handling of

L
Partha Pratim
Das
circumstantial Exceptional Flow from Normal Flow

E
Weekly Recap
• Current state saved in a pre-defined location
Objective &

T
Outline
• Execution switched to a pre-defined handler
Exception

P
Fundamentals
Types of Exceptions
Exception Stages

N
Error Handling in
C Exceptions are C++’s means of separating error reporting from error handling
C Language Features
RV & Params
Local goto – Bjarne Stroustrup
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.8


Types of Exceptions

Module M36

• Asynchronous Exceptions:

L
Partha Pratim
Das
◦ Exceptions that come Unexpectedly

E
Weekly Recap
◦ Example – an Interrupt in a Program
Objective &
◦ Takes control away from the Executing Thread context to a context that is different

T
Outline

Exception from that which caused the exception

P
Fundamentals
Types of Exceptions • Synchronous Exceptions:
Exception Stages

N
Error Handling in ◦ Planned Exceptions
C
C Language Features
◦ Handled in an organized manner
RV & Params ◦ The most common type of Synchronous Exception is implemented as a throw
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.9


Exception Stages

Module M36 [1] Error Incidence


• Synchronous (S/W) Logical Error

L
Partha Pratim
Das
• Asynchronous (H/W) Interrupt (S/W Interrupt)

E
Weekly Recap
[2] Create Object & Raise Exception
Objective &

T
Outline • An Exception Object can be of any Complete Type - an int to a full blown C++ class
Exception object

P
Fundamentals
Types of Exceptions
Exception Stages
[3] Detect Exception

N
Error Handling in • Polling – Software Tests
C
C Language Features
• Notification – Control (Stack) Adjustments
RV & Params
Local goto
[4] Handle Exception
C Standard Library
Support
• Ignore: hope someone else handles it, that is, Do Not Catch
Global Variables • Act: but allow others to handle it afterwards, that is, Catch, Handle and Re-Throw
Abnormal
Termination • Own: take complete ownership, that is, Catch and Handle
Conditional
Termination [5] Recover from Exception
Non-Local goto
Signals • Continue Execution: If handled inside the program
Shortcomings
• Abort Execution: If handled outside the program
Programming in Modern C++ Partha Pratim Das M36.10
Module Summary
Exception Stages

Module M36

int f() {

L
Partha Pratim
Das
int error;

E
Weekly Recap /* ... */
Objective &
if (error) /* Stage 1: error occurred */

T
Outline

Exception return -1; /* Stage 2: generate exception object */

P
Fundamentals
Types of Exceptions
/* ... */
Exception Stages }

N
Error Handling in
C
C Language Features int main(void) {
RV & Params
Local goto if (f() != 0) /* Stage 3: detect exception */
C Standard Library
Support {
Global Variables
Abnormal
/* Stage 4: handle exception */
Termination
Conditional
}
Termination
/* Stage 5: recover */
Non-Local goto
Signals }
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.11


Error Handling in C

Module M36

L
Partha Pratim
Das

E
Weekly Recap

Objective &

T
Outline

Exception

P
Fundamentals
Types of Exceptions
Exception Stages

N
Error Handling in
C
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Error Handling in C
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.12


Support for Error Handling in C

Module M36 • Support for Error Handling in C


◦ C language does not provide any specific feature for error handling. Consequenly,

L
Partha Pratim
Das
developers are forced to use normal programming features in a disciplined way to handle

E
Weekly Recap
errors. This has led to industry practices that the developers should abide by
Objective &
◦ C Standard Library provides a collection of headers that can be used for handling errors in

T
Outline

Exception different contexts. None of them is complete in itself, but together they kind of cover most

P
Fundamentals
situations. This again has led to industry practices that the developers should follow
Types of Exceptions
Exception Stages
• Language Features

N
Error Handling in
C ◦ Return Value & Parameters
C Language Features
RV & Params
◦ Local goto
Local goto
C Standard Library
• Standard Library Support
Support
Global Variables ◦ Global Variables (<errno.h>)
Abnormal
Termination ◦ Abnormal Termination (<stdlib.h>)
Conditional
Termination
◦ Conditional Termination (<assert.h>)
Non-Local goto ◦ Non-Local goto (<setjmp.h>)
Signals
Shortcomings
◦ Signals (<signal.h>)
Module Summary Programming in Modern C++ Partha Pratim Das M36.13
Return Value & Parameters

Module M36

• Function Return Value Mechanism

L
Partha Pratim
Das
◦ Created by the Callee as Temporary Objects

E
Weekly Recap
◦ Passed onto the Caller
Objective &
◦ Caller checks for Error Conditions

T
Outline

Exception ◦ Return Values can be ignored and lost

P
Fundamentals
Types of Exceptions ◦ Return Values are temporary
Exception Stages
• Function (output) Parameter Mechanism

N
Error Handling in
C
C Language Features
◦ Outbound Parameters
RV & Params ◦ Bound to arguments
Local goto
C Standard Library ◦ Offer multiple logical Return Values
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.14


Example: Return Value & Parameters

Module M36
int Push(int i) {

L
Partha Pratim
Das
if (top_ == size-1) // Incidence
return 0; // Raise

E
Weekly Recap
else
Objective &
stack_[++top_] = i;

T
Outline

Exception

P
Fundamentals return 1;
Types of Exceptions
Exception Stages
}

N
Error Handling in
C
C Language Features
int main() {
RV & Params int x;
Local goto
C Standard Library
// ...
Support if (!Push(x)) { // Detect
Global Variables
Abnormal // Handling
Termination
Conditional
}
Termination
// Recovery
Non-Local goto
Signals }
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.15


Local goto

Module M36

• Local goto Mechanism

L
Partha Pratim
Das
◦ (At Source) Escapes: Gets Control out of a Deep Nested Loop

E
Weekly Recap
◦ (At Destination) Refactors: Actions from Multiple Points of Error Inception
Objective &

T
Outline • A group of C Features
Exception
◦ goto Label;

P
Fundamentals
Types of Exceptions
Exception Stages
◦ break continue;

N
Error Handling in ◦ default switch case
C
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.16


Example: Local goto

Module M36
_PHNDLR _cdecl signal(int signum, _PHNDLR sigact)

L
Partha Pratim
Das { // Lifted from VC98\CRT\SRC\WINSIG.C
... /* Check for sigact support */

E
Weekly Recap
if ( (sigact == ...) ) goto sigreterror;
Objective &

T
Outline
/* Not exceptions in the host OS. */
Exception
if ( (signum == ... ) { ... goto sigreterror; }

P
Fundamentals
Types of Exceptions else { ... goto sigretok; }
Exception Stages

N
Error Handling in /* Exceptions in the host OS. */
C
C Language Features
if ( (signum ...) ) goto sigreterror;
RV & Params ...
Local goto sigretok:
C Standard Library
Support return(oldsigact);
Global Variables
Abnormal
Termination sigreterror:
Conditional errno = EINVAL;
Termination
Non-Local goto return(SIG_ERR);
Signals }
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.17


Example: Local goto

Module M36

L
Partha Pratim
Das

E
Weekly Recap

Objective &

T
Outline

Exception

P
Fundamentals
Types of Exceptions
Exception Stages

N
Error Handling in
C
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.18


Example: Local goto

Module M36

L
Partha Pratim
Das

E
Weekly Recap

Objective &

T
Outline

Exception

P
Fundamentals
Types of Exceptions
Exception Stages

N
Error Handling in
C
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.19


Example: Local goto

Module M36

L
Partha Pratim
Das

E
Weekly Recap

Objective &

T
Outline

Exception

P
Fundamentals
Types of Exceptions
Exception Stages

N
Error Handling in
C
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.20


Global Variables

Module M36

• GV Mechanism

L
Partha Pratim
Das
◦ Use a designated Global Error Variable

E
Weekly Recap
◦ Set it on Error
Objective &
◦ Poll / Check it for Detection

T
Outline

Exception
• Standard Library GV Mechanism

P
Fundamentals
Types of Exceptions
Exception Stages
◦ <errno.h>/<cerrno>

N
Error Handling in
C
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.21


Example: Global Variables

Module M36
#include <errno.h>

L
Partha Pratim
Das #include <math.h>
#include <stdio.h>

E
Weekly Recap

Objective &
int main() {

T
Outline
double x, y, result;
Exception
/*... somehow set ’x’ and ’y’ ...*/

P
Fundamentals
Types of Exceptions errno = 0;
Exception Stages

N
Error Handling in result = pow(x, y);
C
C Language Features
RV & Params if (errno == EDOM)
Local goto printf("Domain error on x/y pair \n");
C Standard Library
Support else
Global Variables if (errno == ERANGE)
Abnormal
Termination printf("range error in result \n");
Conditional else
Termination
Non-Local goto printf("x to the y = %d \n", (int) result);
Signals }
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.22


Abnormal Termination

Module M36

• Program Halting Functions provided by

L
Partha Pratim
Das
◦ <stdlib.h>/<cstdlib>

E
Weekly Recap

Objective &
• abort()

T
Outline
◦ Catastrophic Program Failure
Exception
• exit()

P
Fundamentals
Types of Exceptions
Exception Stages ◦ Code Clean up via atexit() Registrations

N
Error Handling in
C • atexit()
C Language Features
RV & Params ◦ Handlers called in reverse order of their Registrations
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.23


Example: Abnormal Termination

Module M36
#include <stdio.h>

L
Partha Pratim
Das
#include <stdlib.h>

static void atexit_handler_1(void) {

E
Weekly Recap
printf("within ’atexit_handler_1’ \n");
Objective &
}

T
Outline

Exception static void atexit_handler_2(void) {

P
Fundamentals
Types of Exceptions
printf("within ’atexit_handler_2’ \n");
Exception Stages
}

N
Error Handling in
C
int main() {
C Language Features
atexit(atexit_handler_1);
RV & Params
atexit(atexit_handler_2);
Local goto exit(EXIT_SUCCESS);
C Standard Library
Support
printf("This line should never appear \n");
Global Variables
Abnormal
Termination return 0;
Conditional }
Termination
Non-Local goto within ’atexit_handler_2’
Signals within ’atexit_handler_1’
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.24


Conditional Termination

Module M36

• Diagnostic ASSERT macro defined in

L
Partha Pratim
Das
◦ <assert.h>/<cassert>

E
Weekly Recap

Objective &
• Assertions valid when NDEBUG macro is not defined (debug build is done)

T
Outline
• Assert calls internal function, reports the source file details and then Terminates
Exception

P
Fundamentals
Types of Exceptions
Exception Stages

N
Error Handling in
C
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.25


Example: Conditional Termination
/* Debug version */
Module M36
//#define NDEBUG
#include <assert.h>

L
Partha Pratim
Das #include <stdlib.h>
#include <stdio.h>

E
Weekly Recap

Objective & /* When run - Asserts */

T
Outline int main() { int i = 0;
Exception assert(++i == 0); // Assert 0 here

P
Fundamentals
Types of Exceptions printf(" i is %d \n", i);
Exception Stages

N
Error Handling in return 0;
C }
C Language Features void _assert(int test, char const * test_image, char const * file, int line) {
RV & Params
if (!test) { printf("assertion failed: %s , file %s , line %d\n", test_image, file, line);
Local goto
abort();
C Standard Library
Support }
Global Variables }
Abnormal
Termination Assertion failed: ++i == 0, // On MSVC++
Conditional file d:\ppd\my courses...\codes\msvc\programming in modern c++\exception in c\assertion.c,
Termination
Non-Local goto line 8
Signals
Shortcomings a.out: main.c:17: main: Assertion ‘++i == 0’ failed. // On onlinegdb
Module Summary Programming in Modern C++ Partha Pratim Das M36.26
Example: Conditional Termination (On MSVC++)

Module M36

L
Partha Pratim
Das

E
Weekly Recap

Objective &

T
Outline

Exception

P
Fundamentals
Types of Exceptions
Exception Stages

N
Error Handling in
C
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.27


Example: Conditional Termination

Module M36 /* Release version */


#define NDEBUG

L
Partha Pratim
Das
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>

E
Weekly Recap

Objective &
/* When run yields ’i’ is 0 */

T
Outline
int main() {
Exception int i = 0;

P
Fundamentals
assert(++i == 0); // Assert 0 here
Types of Exceptions
Exception Stages
printf(" i is %d \n", i);

N
Error Handling in
C
C Language Features
return 0;
RV & Params
}
Local goto void _assert(int test, char const * test_image, char const * file, int line) {
C Standard Library
Support if (!test) {
Global Variables
printf("assertion failed: %s , file %s , line %d\n", test_image, file, line);
Abnormal
Termination abort();
Conditional }
Termination }
Non-Local goto
Signals i is 0
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.28


Non-Local goto

Module M36

• setjmp() and longjmp() functions provided in <setjmp.h> Header along with

L
Partha Pratim
Das
collateral type jmp buf

E
Weekly Recap
• setjmp(jmp buf)
Objective &

T
Outline ◦ Sets the Jump point filling up the jmp buf object with the current program context
Exception
• longjmp(jmp buf, int)

P
Fundamentals
Types of Exceptions
Exception Stages ◦ Effects a Jump to the context of the jmp buf object

N
Error Handling in ◦ Control return to setjmp call last called on jmp buf
C
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.29


Example: Non-Local goto: The Dynamics

Module M36
Caller Callee

L
Partha Pratim
Das #include <stdio.h> jmp_buf jbuf;
#include <stdbool.h>

E
Weekly Recap #include <setjmp.h> void g() {
Objective & bool error = false;

T
Outline int main() { printf("g() started\n");
Exception
if (setjmp(jbuf) == 0) { if (error)
printf("g() called\n"); longjmp(jbuf, 1);

P
Fundamentals
Types of Exceptions g(); printf("g() ended\n");
Exception Stages printf("g() returned\n"); return;

N
Error Handling in } }
C else
C Language Features printf("g() failed\n");
RV & Params return 0;
Local goto }
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.30


Example: Non-Local goto: The Dynamics

Module M36
Caller Callee

L
Partha Pratim
Das int main() { jmp_buf jbuf;
if (setjmp(jbuf) == 0) {

E
Weekly Recap printf("g() called\n"); void g() {
Objective & g(); bool error = false;

T
Outline printf("g() returned\n"); printf("g() started\n");
Exception } if (error)

P
Fundamentals else longjmp(jbuf, 1);
Types of Exceptions printf("g() failed\n"); printf("g() ended\n");
Exception Stages return 0; return;

N
Error Handling in } }
C
C Language Features
RV & Params (1) g() called
Local goto (2) g() successfully returned
C Standard Library
Support
Global Variables g() called
Abnormal g() started
Termination
Conditional
g() ended
Termination g() returned
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.31


Example: Non-Local goto: The Dynamics

Module M36
Caller Callee

L
Partha Pratim
Das int main() { jmp_buf jbuf;
if (setjmp(jbuf) == 0) {

E
Weekly Recap printf("g() called\n"); void g() {
Objective & g(); bool error = true;

T
Outline printf("g() returned\n"); printf("g() started\n");
Exception } if (error)

P
Fundamentals else longjmp(jbuf, 1);
Types of Exceptions printf("g() failed\n"); printf("g() ended\n");
Exception Stages return 0; return;

N
Error Handling in } }
C
C Language Features
RV & Params (1) g() called
Local goto (2) longjmp executed
C Standard Library (3) setjmp takes to handler
Support
Global Variables
Abnormal g() called
Termination
Conditional
g() started
Termination g() failed
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.32


Example: Non-Local goto
#include <setjmp.h>
Module M36
#include <stdio.h>

L
Partha Pratim
Das jmp_buf j;

E
Weekly Recap
void raise_exception() {
Objective & printf("Exception raised. \n");

T
Outline longjmp(j, 1); /* Jump to exception handler */
Exception printf("This line should never appear \n");

P
Fundamentals }
Types of Exceptions int main() {
Exception Stages
if (setjmp(j) == 0) {

N
Error Handling in printf("’setjmp’ is initializing j. \n");
C raise_exception();
C Language Features printf("This line should never appear \n");
RV & Params
}
Local goto
else
C Standard Library
Support printf("’setjmp’ was just jumped into. \n");
Global Variables /* The exception handler code here */
Abnormal return 0 ;
Termination
}
Conditional
Termination
Non-Local goto ’setjmp’ is initializing j.
Signals Exception raised.
Shortcomings ’setjmp’ was just jumped into.
Module Summary Programming in Modern C++ Partha Pratim Das M36.33
Signals

Module M36

• Header <signal.h>

L
Partha Pratim
Das
• raise()

E
Weekly Recap

Objective &
◦ Sends a signal to the executing program

T
Outline
• signal()
Exception
◦ Registers interrupt signal handler

P
Fundamentals
Types of Exceptions
Exception Stages ◦ Returns the previous handler associated with the given signal

N
Error Handling in
C • Converts h/w interrupts to s/w interrupts
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.34


Example: Signals

Module M36
// Use signal to attach a signal

L
Partha Pratim
Das
// handler to the abort routine
#include <stdio.h>

E
Weekly Recap #include <stdlib.h>
#include <signal.h>
Objective &

T
Outline
void SignalHandler(int signal) {
Exception printf("Application aborting...\n");

P
Fundamentals
Types of Exceptions
}
Exception Stages
int main() {

N
Error Handling in
C
typedef void (*SignalHandlerPointer)(int);
C Language Features
RV & Params
SignalHandlerPointer previousHandler;
Local goto
C Standard Library previousHandler = signal(SIGABRT, SignalHandler);
Support
Global Variables
abort();
Abnormal
Termination
Conditional return 0;
Termination
}
Non-Local goto
Signals Application aborting...
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.35


Shortcomings

Module M36

• Destructor-ignorant:

L
Partha Pratim
Das
◦ Cannot release Local Objects i.e. Resources Leak

E
Weekly Recap

Objective &
• Obtrusive:

T
Outline
◦ Interrogating RV or GV results in Code Clutter
Exception
• Inflexible:

P
Fundamentals
Types of Exceptions
Exception Stages ◦ Spoils Normal Function Semantics

N
Error Handling in
C • Non-native:
C Language Features
RV & Params ◦ Require Library Support outside Core Language
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.36


Module Summary

Module M36

• Introduced the concept of exceptions

L
Partha Pratim
Das
• Discussed error handling in C

E
Weekly Recap

Objective &
• Illustrated various language features and library support in C for handling errors

T
Outline

Exception
• Demonstrated with examples

P
Fundamentals
Types of Exceptions
Exception Stages

N
Error Handling in
C
C Language Features
RV & Params
Local goto
C Standard Library
Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Module Summary Programming in Modern C++ Partha Pratim Das M36.37


Module M37

L
Partha Pratim
Das
Programming in Modern C++

E
Objectives &
Outlines
Module M37: Exceptions (Error handling in C++): Part 2

T
Exceptions in
C++
try-throw-catch

P
Exception Scope
(try)
Exception Arguments Partha Pratim Das

N
(catch)
Exception Matching
Exception Raise
(throw) Department of Computer Science and Engineering
Advantages Indian Institute of Technology, Kharagpur
std::exception
Module Summary [email protected]

All url’s in this module have been accessed in September, 2021 and found to be functional

Programming in Modern C++ Partha Pratim Das M37.1


Module Recap

Module M37

• Introduced the concept of exceptions

L
Partha Pratim
Das
• Discussed error handling in C

E
Objectives &
Outlines • Illustrated various language features and library support in C for handling errors

T
Exceptions in
C++ • Demonstrated with examples
try-throw-catch

P
Exception Scope
(try)
Exception Arguments

N
(catch)
Exception Matching
Exception Raise
(throw)
Advantages
std::exception
Module Summary

Programming in Modern C++ Partha Pratim Das M37.2


Module Objectives

Module M37

• Understand the Error handling in C++

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Exceptions in
C++
try-throw-catch

P
Exception Scope
(try)
Exception Arguments

N
(catch)
Exception Matching
Exception Raise
(throw)
Advantages
std::exception
Module Summary

Programming in Modern C++ Partha Pratim Das M37.3


Module Outline

Module M37

L
Partha Pratim
Das
1 Exceptions in C++

E
Objectives &
Outlines try-throw-catch

T
Exceptions in Exception Scope (try)
C++
try-throw-catch Exception Arguments (catch)

P
Exception Scope
(try) Exception Matching
Exception Arguments
Exception Raise (throw)

N
(catch)
Exception Matching
Exception Raise
Advantages
(throw)
Advantages
std::exception
std::exception
Module Summary

2 Module Summary

Programming in Modern C++ Partha Pratim Das M37.4


Exceptions in C++

Module M37

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Exceptions in
C++
try-throw-catch

P
Exception Scope
(try)
Exception Arguments

N
(catch)
Exception Matching
Exception Raise
(throw)
Advantages
std::exception
Module Summary
Exceptions in C++

Programming in Modern C++ Partha Pratim Das M37.5


Expectations

Module M37

• Separate Error-Handling code from Normal code

L
Partha Pratim
Das
• Language Mechanism rather than of the Library

E
Objectives &
Outlines • Compiler for Tracking Automatic Variables

T
Exceptions in
C++ • Schemes for Destruction of Dynamic Memory
try-throw-catch

P
Exception Scope
(try)
• Less Overhead for the Designer
Exception Arguments
• Exception Propagation from the deepest of levels

N
(catch)
Exception Matching
Exception Raise • Various Exceptions handled by a single Handler
(throw)
Advantages
std::exception
Module Summary

Programming in Modern C++ Partha Pratim Das M37.6


Error Handling Dynamics: C and C++
Header Caller Callee
Module M37
C Scenario

L
Partha Pratim
Das
#include <stdio.h> int main() { jmp_buf jbuf;
#include <stdbool.h> if (setjmp(jbuf) == 0) { void g() {

E
Objectives &
Outlines #include <setjmp.h> printf("g() called\n"); bool error = false;
g(); printf("g() started\n");

T
Exceptions in
C++
printf("g() returned\n"); if (error)
try-throw-catch } longjmp(jbuf, 1);

P
Exception Scope else printf("g() failed\n"); // On longjmp printf("g() ended\n");
(try) return 0; return;
Exception Arguments } }

N
(catch)
Exception Matching
Exception Raise C++ Scenario
(throw)
Advantages #include <iostream> int main() { class Excp: public exception {};
std::exception
#include <exception> try { void g() {
Module Summary using namespace std; cout << "g() called\n"; bool error = false;
g(); cout << "g() started\n";
cout << "g() returned\n"; if (error)
} throw Excp();
catch (Excp&) { cout << "g() failed\n"; } cout << "g() ended\n";
return 0; return;
} }
Programming in Modern C++ Partha Pratim Das M37.7
try-throw-catch

Module M37
Caller Callee

L
Partha Pratim
Das int main() { class Excp: public exception {};
try { void g() {

E
Objectives & cout << "g() called\n"; bool error = false;
Outlines
g(); cout << "g() started\n";

T
Exceptions in cout << "g() returned\n"; if (error)
C++
} throw Excp();
try-throw-catch
catch (Excp&) { cout << "g() failed\n"; }

P
cout << "g() ended\n";
Exception Scope
(try) return 0; return;
Exception Arguments } }

N
(catch)
Exception Matching
Exception Raise
(throw)
(1) g() called
Advantages
(2) g() successfully returned
std::exception
Module Summary g() called
g() started
g() ended
g() returned

Programming in Modern C++ Partha Pratim Das M37.8


try-throw-catch

Module M37 Caller Callee

L
Partha Pratim int main() { class Excp: public exception {};
Das
try { class A {};
cout << "g() called\n"; void g() { A a;

E
Objectives &
Outlines g(); bool error = true;
cout << "g() returned\n"; cout << "g() started\n";

T
Exceptions in
C++
} if (error)
try-throw-catch catch (Excp&) { cout << "g() failed\n"; } throw Excp();

P
Exception Scope return 0; cout << "g() ended\n";
(try) } return;
Exception Arguments }

N
(catch)
Exception Matching
Exception Raise
(throw) (1) g() called
Advantages (2) Exception raised
std::exception (3) Stack frame of g() unwinds and destructor of a called
Module Summary (4) Remaining execution of g() and cout skipped
(5) Exception caught by catch clause
(6) Normal flow continues

g() called
g() started
g() failed
Programming in Modern C++ Partha Pratim Das M37.9
Exception Flow
#include <iostream> void f() { MyClass f_a;
Module M37
#include <exception> try { g();
using namespace std; bool okay = true; // Not executed

L
Partha Pratim
Das class MyException: public exception { }; }
class MyClass { public: ~MyClass() { } }; // Catches exception from Line 3

E
Objectives & void h() { MyClass h_a; catch (MyException) { cout << "MyException\n"; }
Outlines
//throw 1; // Line 1 // Catches exception from Line 4

T
Exceptions in //throw 2.5; // Line 2 catch (exception) { cout << "exception\n"; }
C++
//throw MyException(); // Line 3 // Catches exception from Line 5 & passes on
try-throw-catch
//throw exception(); // Line 4

P
Exception Scope
catch (...) { throw; }
(try) //throw MyClass(); // Line 5 } // Stack unwind, f_a.~MyClass() called
Exception Arguments } // Stack unwind, h_a.~MyClass() called

N
(catch)
// Passes on all exceptions int main() {
Exception Matching
void g() { MyClass g_a; try { f();
Exception Raise
(throw) try { h(); bool okay = true; // Not executed
Advantages bool okay = true; // Not executed }
std::exception } // Catches exception from Line 5
Module Summary // Catches exception from Line 1 catch (...) { cout << "Unknown\n"; }
catch (int) { cout << "int\n"; }
// Catches exception from Line 2 cout << "End of main()\n";
catch (double) { cout << "double\n"; } }
// Catches exception from Line 3-5 & passes on
catch (...) { throw; }
} // Stack unwind, g_a.~MyClass() called

Programming in Modern C++ Partha Pratim Das M37.10


try Block: Exception Scope

Module M37 • try block


◦ Consolidate areas that might throw exceptions

L
Partha Pratim
Das
• function try block

E
Objectives &
Outlines ◦ Area for detection is the entire function body

T
Exceptions in
C++ • Nested try block
try-throw-catch
◦ Semantically equivalent to nested function calls

P
Exception Scope
(try)
Exception Arguments

N
(catch) Function try Nested try
Exception Matching
Exception Raise
void f() try {
(throw)
Advantages
try { try { throw E(); }
std::exception throw E(); catch (E& e) { }
Module Summary
} }
catch (E& e) { catch (E& e1) {
} }
Note: The usual curly braces for the
function scope are not to be put here
Programming in Modern C++ Partha Pratim Das M37.11
catch Block: Exception Arguments

Module M37

• catch block

L
Partha Pratim
Das
◦ Name for the Exception Handler

E
Objectives &
Outlines ◦ Catching an Exception is like invoking a function
◦ Immediately follows the try block

T
Exceptions in
C++
try-throw-catch ◦ Unique Formal Parameter for each Handler

P
Exception Scope
(try)
◦ Can simply be a Type Name to distinguish its Handler from others
Exception Arguments

N
(catch)
Exception Matching
Exception Raise
(throw)
Advantages
std::exception
Module Summary

Programming in Modern C++ Partha Pratim Das M37.12


try-catch: Exception Matching

Module M37

• Exact Match

L
Partha Pratim
Das
◦ The catch argument type matches the type of the thrown object

E
Objectives &
Outlines . No implicit conversion is allowed

T
Exceptions in
C++ • Generalization / Specialization
try-throw-catch
◦ The catch argument is a public base class of the thrown class object

P
Exception Scope
(try)
Exception Arguments • Pointer

N
(catch)
Exception Matching ◦ Pointer types – convertible by standard conversion
Exception Raise
(throw)
Advantages
std::exception
Module Summary

Programming in Modern C++ Partha Pratim Das M37.13


try-catch: Exception Matching

Module M37

• In the order of appearance with matching

L
Partha Pratim
Das
• If Base Class catch block precedes Derived Class catch block

E
Objectives &
Outlines ◦ Compiler issues a warning and continues

T
Exceptions in
C++
◦ Unreachable code (derived class handler) ignored
try-throw-catch
• catch(...) block must be the last catch block because it catches all exceptions

P
Exception Scope
(try)
Exception Arguments • If no matching Handler is found in the current scope, the search continues to find a

N
(catch)
Exception Matching matching handler in a dynamically surrounding try block
Exception Raise
(throw) ◦ Stack Unwinds
Advantages
std::exception • If eventually no handler is found, terminate() is called
Module Summary

Programming in Modern C++ Partha Pratim Das M37.14


throw Expression: Exception Raise

Module M37

• Expression is treated the same way as

L
Partha Pratim
Das
◦ A function argument in a call or the operand of a return statement

E
Objectives &
Outlines • Exception Context

T
Exceptions in
C++ ◦ class Exception { };
try-throw-catch
• The Expression

P
Exception Scope
(try)
Exception Arguments ◦ Generate an Exception object to throw

N
(catch)
Exception Matching . throw Exception();
Exception Raise
(throw)
Advantages
◦ Or, Copies an existing Exception object to throw
std::exception
. Exception ex;
Module Summary
. ...
. throw ex; // Exception(ex);
• Exception object is created on the Free Store

Programming in Modern C++ Partha Pratim Das M37.15


throw Expression: Restrictions

Module M37

• For a UDT Expression

L
Partha Pratim
Das
◦ Copy Constructor and Destructor should be supported

E
Objectives &
Outlines • The type of Expression cannot be an incomplete type or a pointer to an incomplete type

T
Exceptions in
C++ ◦ No incomplete type like void, array of unknown size or of elements of incomplete
try-throw-catch
type, Declared but not Defined struct / union / enum / class Objects or

P
Exception Scope
(try)
Exception Arguments
Pointers to such Objects

N
(catch)
◦ No pointer to an incomplete type, except void*, const void*, volatile void*,
Exception Matching
Exception Raise const volatile void*
(throw)
Advantages
std::exception
Module Summary

Programming in Modern C++ Partha Pratim Das M37.16


(re)-throw: Throwing Again?

Module M37

• Re-throw

L
Partha Pratim
Das
◦ catch may pass on the exception after handling

E
Objectives &
Outlines ◦ Re-throw is not same as throwing again!

T
Exceptions in
C++
try-throw-catch Throws again Re-throw

P
Exception Scope
(try) try { ... } try { ... }
Exception Arguments
catch (Exception& ex) { catch (Exception& ex) {

N
(catch)
Exception Matching
Exception Raise
// Handle and // Handle and
(throw)
Advantages
... ...
std::exception // Raise again // Pass-on
Module Summary throw ex; throw;
// ex copied // No copy
// ex destructed // No Destruction
} }

Programming in Modern C++ Partha Pratim Das M37.17


Advantages

Module M37

• Destructor-savvy:

L
Partha Pratim
Das
◦ Stack unwinds; Orderly destruction of Local-objects

E
Objectives &
Outlines • Unobtrusive:

T
Exceptions in
C++ ◦ Exception Handling is implicit and automatic
try-throw-catch
◦ No clutter of error checks

P
Exception Scope
(try)
Exception Arguments • Precise:

N
(catch)
Exception Matching ◦ Exception Object Type designed using semantics
Exception Raise
(throw)
Advantages
• Native and Standard:
std::exception ◦ EH is part of the C++ language
Module Summary
◦ EH is available in all standard C++ compilers

Programming in Modern C++ Partha Pratim Das M37.18


Advantages

Module M37

• Scalable:

L
Partha Pratim
Das
◦ Each function can have multiple try blocks

E
Objectives &
Outlines ◦ Each try block can have a single Handler or a group of Handlers
◦ Each Handler can catch a single type, a group of types, or all types

T
Exceptions in
C++
try-throw-catch • Fault-tolerant:

P
Exception Scope
(try)
Exception Arguments
◦ Functions can specify the exception types to throw; Handlers can specify the

N
(catch)
exception types to catch
Exception Matching
Exception Raise ◦ Violation behavior of these specifications is predictable and user-configurable
(throw)
Advantages
std::exception
Module Summary

Programming in Modern C++ Partha Pratim Das M37.19


Exceptions in Standard Library: std::exception

Module M37
All objects thrown by components of the standard library are derived from this class.

L
Partha Pratim
Das Therefore, all standard exceptions can be caught by catching this type by reference.

E
Objectives &
Outlines
class exception {
public:

T
Exceptions in
C++
exception() throw();
try-throw-catch

P
Exception Scope exception(const exception&) throw();
(try)
Exception Arguments exception& operator=(const exception&) throw();

N
(catch)
Exception Matching virtual ~exception() throw();
Exception Raise
(throw) virtual const char* what() const throw();
Advantages
std::exception
}
Module Summary
Sources: std::exception and std::exception in C++11, C++14, C++17 & C++20

Programming in Modern C++ Partha Pratim Das M37.20


Exceptions in Standard Library: std::exception

Module M37

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Exceptions in
C++
try-throw-catch

P
Exception Scope
(try)
Exception Arguments

N
(catch)
Exception Matching
Exception Raise
(throw)
Advantages
std::exception
Module Summary

Sources: Standard Library Exception Hierarchy

Programming in Modern C++ Partha Pratim Das M37.21


Exceptions in Standard Library: std::exception

Module M37
• logic error: Faulty logic like violating logical preconditions or class invariants (may be

L
Partha Pratim
Das
preventable)
◦ invalid argument: An argument value has not been accepted

E
Objectives &
Outlines ◦ domain error: Situations where the inputs are outside of the domain for an operation
◦ length error: Exceeding implementation defined length limits for some object

T
Exceptions in
C++
try-throw-catch ◦ out of range: Attempt to access elements out of defined range

P
Exception Scope
(try) • runtime error: Due to events beyond the scope of the program and can not be easily
Exception Arguments predicted

N
(catch)
Exception Matching
Exception Raise
◦ range error: Result cannot be represented by the destination type
(throw) ◦ overflow error: Arithmetic overflow errors (Result is too large for the destination type)
Advantages
std::exception ◦ underflow error: Arithmetic underflow errors (Result is a subnormal floating-point value)
Module Summary • bad typeid: Exception thrown on typeid of null pointer
• bad cast: Exception thrown on failure to dynamic cast
• bad alloc: Exception thrown on failure allocating memory
• bad exception: Exception thrown by unexpected handler
Sources: std::exception and std::exception in C++11, C++14, C++17 & C++20
Programming in Modern C++ Partha Pratim Das M37.22
Exceptions in Standard Library: std::exception:
C++98, C++11, C++14, C++17 & C++20
Module M37
• logic error • bad typeid
◦ invalid argument • bad cast

L
Partha Pratim
Das
◦ domain error ◦ bad any cast (C++17)
◦ length error

E
Objectives & • bad weak ptr (C++11)
Outlines
◦ out of range • bad function call (C++11)

T
Exceptions in
C++
◦ future error (C++11) • bad alloc
try-throw-catch • bad optional access (C++17) ◦ bad array new length (C++11)

P
Exception Scope
(try)
• runtime error • bad exception
Exception Arguments ◦ range error • ios base::failure (until C++11)

N
(catch)
Exception Matching ◦ overflow error • bad variant access (C++17)
Exception Raise
(throw)
◦ underflow error
Advantages
◦ regex error (C++11)
std::exception ◦ system error (C++11)
Module Summary . ios base::failure (C++11)
. filesystem::filesystem error (C++17)
◦ txtion (TM TS)
◦ nonexistent local time (C++20)
◦ ambiguous local time (C++20)
◦ format error (C++20)
Programming in Modern C++ Partha Pratim Das M37.23
Module Summary

Module M37

• Discussed exception (error) handling in C++

L
Partha Pratim
Das
• Illustrated try-throw-catch feature in C++ for handling errors

E
Objectives &
Outlines • Demonstrated with examples

T
Exceptions in
C++
try-throw-catch

P
Exception Scope
(try)
Exception Arguments

N
(catch)
Exception Matching
Exception Raise
(throw)
Advantages
std::exception
Module Summary

Programming in Modern C++ Partha Pratim Das M37.24


Module M38

L
Partha Pratim
Das
Programming in Modern C++

E
Objectives &
Outlines
Module M38: Template (Function Template): Part 1

T
What is a
Template?

P
Function
Template
Definition
Partha Pratim Das

N
Instantiation
Template Argument
Deduction
Example Department of Computer Science and Engineering
typename
Indian Institute of Technology, Kharagpur

Module Summary [email protected]

All url’s in this module have been accessed in September, 2021 and found to be functional

Programming in Modern C++ Partha Pratim Das M38.1


Module Recap

Module M38

• Discussed exception (error) handling in C++

L
Partha Pratim
Das
• Illustrated try-throw-catch feature in C++ for handling errors

E
Objectives &
Outlines • Demonstrated with examples

T
What is a
Template?

P
Function
Template
Definition

N
Instantiation
Template Argument
Deduction
Example

typename

Module Summary

Programming in Modern C++ Partha Pratim Das M38.2


Module Objectives

Module M38

• Understand Templates in C++

L
Partha Pratim
Das
• Understand Function Templates

E
Objectives &
Outlines

T
What is a
Template?

P
Function
Template
Definition

N
Instantiation
Template Argument
Deduction
Example

typename

Module Summary

Programming in Modern C++ Partha Pratim Das M38.3


Module Outline

Module M38

L
Partha Pratim
Das 1 What is a Template?

E
Objectives &
Outlines

T
What is a 2 Function Template
Template?
Definition

P
Function
Template Instantiation
Definition
Template Argument Deduction

N
Instantiation
Template Argument
Deduction Example
Example

typename

Module Summary 3 typename

4 Module Summary

Programming in Modern C++ Partha Pratim Das M38.4


What is a Template?

Module M38

L
Partha Pratim
Das

E
Objectives &
Outlines

T
What is a
Template?

P
Function
Template
Definition

N
Instantiation
Template Argument
Deduction
Example

typename

Module Summary
What is a Template?

Programming in Modern C++ Partha Pratim Das M38.5


What is a Template?

Module M38

• Templates are specifications of a collection of functions or classes which are

L
Partha Pratim
Das
parameterized by types

E
Objectives &
Outlines • Examples:

T
What is a
Template?
◦ Function search, min etc.
. The basic algorithms in these functions are the same independent of types

P
Function
Template
Definition
. Yet, we need to write different versions of these functions for strong type

N
Instantiation
Template Argument
checking in C++
Deduction
Example
◦ Classes list, queue etc.
typename . The data members and the methods are almost the same for list of numbers, list
Module Summary of objects
. Yet, we need to define different classes

Programming in Modern C++ Partha Pratim Das M38.6


Function Template

Module M38

L
Partha Pratim
Das

E
Objectives &
Outlines

T
What is a
Template?

P
Function
Template
Definition

N
Instantiation
Template Argument
Deduction
Example

typename

Module Summary
Function Template

Programming in Modern C++ Partha Pratim Das M38.7


Function Template: Code reuse in Algorithms

Module M38 • We need to compute the maximum of two values that can be of:
◦ int

L
Partha Pratim
Das
◦ double

E
Objectives &
Outlines ◦ char * (C-String)
◦ Complex (user-defined class for complex numbers)

T
What is a
Template?
◦ ...

P
Function
Template • We can do this with overloaded Max functions:
Definition

N
Instantiation int Max(int x, int y);
Template Argument
Deduction
double Max(double x, double y);
Example char *Max(char *x, char *y);
Complex Max(Complex x, Complex y);
typename

Module Summary
With every new type, we need to add an overloaded function in the library!
• Issues in Max function
◦ Same algorithm (compare two values using the appropriate operator of the type and return
the larger value)
◦ Different code versions of these functions for strong type checking in C++
Programming in Modern C++ Partha Pratim Das M38.8
Max as Overload
#include <iostream>
Module M38
#include <cstring>
#include <cmath>

L
Partha Pratim
Das using namespace std;
// Overloads of Max

E
Objectives &
Outlines
int Max(int x, int y) { return x > y ? x : y; }
double Max(double x, double y) { return x > y ? x : y; }

T
What is a char *Max(char *x, char *y) { return strcmp(x, y) > 0 ? x : y; }
Template?

P
Function int main() { int a = 3, b = 5, iMax; double c = 2.1, d = 3.7, dMax;
Template
cout << "Max(" << a << ", " << b << ") = " << Max(a, b) << endl;
Definition
cout << "Max(" << c << ", " << d << ") = " << Max(c, d) << endl;

N
Instantiation
Template Argument
Deduction char *s1 = new char[6], *s2 = new char[6];
Example strcpy(s1, "black"); strcpy(s2, "white");
typename cout << "Max(" << s1 << ", " << s2 << ") = " << Max(s1, s2) << endl;
strcpy(s1, "white"); strcpy(s2, "black");
Module Summary
cout << "Max(" << s1 << ", " << s2 << ") = " << Max(s1, s2) << endl;
}

• Overloaded solutions work


• In some cases (C-string), similar algorithms have exceptions
• With every new type, a new overloaded Max is needed
• Can we make Max generic and make a library to work with future types?
• How about macros?
Programming in Modern C++ Partha Pratim Das M38.9
Max as a Macro

Module M38 #include <iostream>


using namespace std;

L
Partha Pratim
Das
// Max as a macro

E
Objectives & #define Max(x, y) (((x) > (y))? x: y)
Outlines

T
What is a int main() {
Template? int a = 3, b = 5;
double c = 2.1, d = 3.7;

P
Function
Template
Definition cout << "Max(" << a << ", " << b << ") = " << Max(a, b) << endl; // Output: Max(3, 5) = 5

N
Instantiation
Template Argument
Deduction
cout << "Max(" << c << ", " << d << ") = " << Max(c, d) << endl; // Output: Max(2.1, 3.7) = 3.7
Example
return 0;
typename
}
Module Summary
• Max, being a macro, is type oblivious – can be used for int as well as double, etc.
• Note the parentheses around parameters to protect precedence
• Note the parentheses around the whole expression to protect precedence
• Looks like a function – but does not behave as such

Programming in Modern C++ Partha Pratim Das M38.10


Max as a Macro: Pitfalls
#include <iostream>
Module M38
#include <cstring>
using namespace std;

L
Partha Pratim
Das
#define Max(x, y) (((x) > (y))? x: y)

E
Objectives &
Outlines
int main() { int a = 3, b = 5; double c = 2.1, d = 3.7;

T
What is a // Side Effects
Template?
cout << "Max(" << a << ", " << b << ") = "; // Output: Max(3, 5) = 6

P
Function cout << Max(a++, b++) << endl;
Template
cout << "a = " << a << ", b = " << b << endl; // Output: a = 4, b = 7
Definition

N
Instantiation
Template Argument
// C-String Comparison
Deduction char *s1 = new char[6], *s2 = new char[6];
Example strcpy(s1, "black"); strcpy(s2, "white");
typename cout << "Max(" << s1 << ", " << s2 << ") = " << Max(s1, s2) << endl; // Max(black, white) = white
Module Summary
strcpy(s1, "white"); strcpy(s2, "black");
cout << "Max(" << s1 << ", " << s2 << ") = " << Max(s1, s2) << endl; // Max(white, black) = black
}

• In ”Side Effects” – the result is wrong, the larger values gets incremented twice
• In ”C-String Comparison” – swapping parameters changes the result – actually compares pointers

Programming in Modern C++ Partha Pratim Das M38.11


Function Template

Module M38

• A function template

L
Partha Pratim
Das
◦ describes how a function should be built

E
Objectives &
Outlines ◦ supplies the definition of the function using some arbitrary types, (as place holders)

T
What is a
Template?
. a parameterized definition
◦ can be considered the definition for a set of overloaded versions of a function

P
Function
Template
Definition
◦ is identified by the keyword template

N
Instantiation
Template Argument
. followed by comma-separated list of parameter identifiers (each preceded by
Deduction
Example
keyword class or keyword typename)
typename
. enclosed between < and > delimiters
Module Summary . followed by the signature the function
◦ Note that every template parameter is a built-in type or class – type parameters

Programming in Modern C++ Partha Pratim Das M38.12


Max as a Function Template

Module M38 #include <iostream>


using namespace std;

L
Partha Pratim
Das
template<class T>

E
Objectives & T Max(T x, T y) {
Outlines
return x > y ? x : y;

T
What is a }
Template?
int main() {

P
Function
Template int a = 3, b = 5, iMax;
Definition double c = 2.1, d = 3.7, dMax;

N
Instantiation
Template Argument
Deduction
iMax = Max<int>(a, b);
Example cout << "Max(" << a << ", " << b << ") = " << iMax << endl; // Output: Max(3, 5) = 5
typename
dMax = Max<double>(c, d);
Module Summary cout << "Max(" << c << ", " << d << ") = " << dMax << endl; // Output: Max(2.1, 3.7) = 3.7
}

• Max, now, knows the type


• Template type parameter T explicitly specified in instantiation of Max<int>, Max<double>

Programming in Modern C++ Partha Pratim Das M38.13


Max as a Function Template: Pitfall ”Side Effects” – Solved

Module M38 #include <iostream>


using namespace std;

L
Partha Pratim
Das
template<class T>

E
Objectives & T Max(T x, T y) {
Outlines
return x > y ? x : y;

T
What is a }
Template?
int main() {

P
Function
Template int a = 3, b = 5, iMax;
Definition

N
Instantiation // Side Effects
Template Argument
Deduction
cout << "Max(" << a << ", " << b << ") = ";
Example iMax = Max<int>(a++, b++);
cout << iMax << endl; // Output: Max(3, 5) = 5
typename

Module Summary cout << "a = " << a << ", b = " << b << endl; // Output: a = 4, b = 6
}

• Max is now a proper function call – no side effect

Programming in Modern C++ Partha Pratim Das M38.14


Max as a Function Template: Pitfall ”C-String Comparison” –
Solved
Module M38 #include <iostream>
#include <cstring>

L
Partha Pratim
Das using namespace std;

E
Objectives & template<class T> T Max(T x, T y) { return x > y ? x : y; }
Outlines

T
What is a template<> // Template specialization for ’char *’ type
Template? char *Max<char *>(char *x, char *y) { return strcmp(x, y) > 0 ? x : y; }

P
Function
Template int main() { char *s1 = new char[6], *s2 = new char[6];
Definition strcpy(s1, "black"); strcpy(s2, "white");

N
Instantiation cout << "Max(" << s1 << ", " << s2 << ") = " << Max<char*>(s1, s2) << endl;
Template Argument
Deduction
// Output: Max(black, white) = white
Example
strcpy(s1, "white"); strcpy(s2, "black");
typename
cout << "Max(" << s1 << ", " << s2 << ") = " << Max<char*>(s1, s2) << endl;
Module Summary // Output: Max(black, white) = white
}

• Generic template code does not work for C-Strings as it compares pointers, not the strings pointed by them
• We provide a specialization to compare pointers using comparison of strings
• Need to specify type explicitly is bothersome

Programming in Modern C++ Partha Pratim Das M38.15


Max as a Function Template: Implicit Instantiation

Module M38 #include <iostream>


using namespace std;

L
Partha Pratim
Das
template<class T> T Max(T x, T y) { return x > y ? x : y; }

E
Objectives &
Outlines
int main() { int a = 3, b = 5, iMax; double c = 2.1, d = 3.7, dMax;

T
What is a iMax = Max(a, b); // Type ’int’ inferred from ’a’ and ’b’ parameters types
Template? cout << "Max(" << a << ", " << b << ") = " << iMax << endl;
// Output: Max(3, 5) = 5

P
Function
Template
Definition dMax = Max(c, d); // Type ’double’ inferred from ’c’ and ’d’ parameters types

N
Instantiation cout << "Max(" << c << ", " << d << ") = " << dMax << endl;
Template Argument
Deduction
// Output: Max(2.1, 3.7) = 3.7
Example }
typename
• Often template type parameter T may be inferred from the type of parameters in the instance
Module Summary • If the compiler cannot infer or infers wrongly, we use explicit instantiation

Programming in Modern C++ Partha Pratim Das M38.16


Template Argument Deduction: Implicit Instantiation

Module M38
• Each item in the template parameter list is a template argument

L
Partha Pratim
Das
• When a template function is invoked, the values of the template arguments are determined by seeing
the types of the function arguments

E
Objectives &
Outlines template<class T> T Max(T x, T y);

T
What is a template<> char *Max<char *>(char *x, char *y);
Template? template <class T, int size> T Max(T x[size]);

P
Function
Template int a, b; Max(a, b); // Binds to Max<int>(int, int);
Definition double c, d; Max(c, d); // Binds to Max<double>(double, double);

N
Instantiation char *s1, *s2; Max(s1, s2); // Binds to Max<char*>(char*, char*);
Template Argument
Deduction
Example
int pval[9]; Max(pval); // Error!
typename • Three kinds of conversions are allowed
Module Summary
◦ L-value transformation (for example, Array-to-pointer conversion)
◦ Qualification conversion
◦ Conversion to a base class instantiation from a class template
• If the same template parameter are found for more than one function argument, template argument
deduction from each function argument must be the same

Programming in Modern C++ Partha Pratim Das M38.17


Max as a Function Template: With User-Defined Class

Module M38 #include <iostream>


#include <cmath>

L
Partha Pratim
Das #include <cstring>
using namespace std;

E
Objectives &
Outlines
class Complex { double re_; double im_; public:

T
What is a Complex(double re = 0.0, double im = 0.0) : re_(re), im_(im) { };
Template? double norm() const { return sqrt(re_*re_+im_*im_); }
friend bool operator>(const Complex& c1, const Complex& c2) { return c1.norm() > c2.norm(); }

P
Function
Template friend ostream& operator<<(ostream& os, const Complex& c) {
Definition os << "(" << c.re_ << ", " << c.im_ << ")"; return os;

N
Instantiation }
Template Argument
Deduction
};
Example template<class T> T Max(T x, T y) { return x > y ? x : y; }
template<> char *Max<char *>(char *x, char *y) { return strcmp(x, y) > 0 ? x : y; }
typename

Module Summary int main() { Complex c1(2.1, 3.2), c2(6.2, 7.2);


cout << "Max(" << c1 << ", " << c2 << ") = " << Max(c1, c2) << endl;
// Output: Max((2.1, 3.2), (6.2, 7.2)) = (6.2, 7.2)
}

• When Max is instantiated with class Complex, we need comparison operator for Complex
• The code, therefore, will not compile without bool operator>(const Complex&, const Complex&)
• Traits of type variable T include bool operator>(T, T) which the instantiating type must fulfill
Programming in Modern C++ Partha Pratim Das M38.18
Max as a Function Template: Overloads

Module M38 #include <iostream>


#include <cstring>

L
Partha Pratim
Das using namespace std;

E
Objectives & template<class T> T Max(T x, T y) { return x > y ? x : y; }
Outlines

T
What is a template<> char *Max<char *>(char *x, char *y) // Template specialization
Template? { return strcmp(x, y) > 0 ? x : y; }

P
Function
Template template<class T, int size> T Max(T x[size]) { // Overloaded template function
Definition T t = x[0];

N
Instantiation for (int i = 0; i < size; ++i) { if (x[i] > t) t = x[i]; }
Template Argument
Deduction
Example return t;
}
typename

Module Summary int main() {


int arr[] = { 2, 5, 6, 3, 7, 9, 4 };
cout << "Max(arr) = " << Max<int, 7>(arr) << endl; // Output: Max(arr) = 9
}

• Template function can be overloaded


• A template parameter can be non-type (int) constant

Programming in Modern C++ Partha Pratim Das M38.19


Swap as a Function Template

Module M38 #include <iostream>


#include <string>

L
Partha Pratim
Das using namespace std;

E
Objectives & template<class T> void Swap(T& one, T& other) { T temp;
Outlines
temp = one; one = other; other = temp;

T
What is a }
Template? int main() { int i = 10, j = 20;
cout << "i = " << i << ", j = " << j << endl;

P
Function
Template Swap(i, j);
Definition cout << "i = " << i << ", j = " << j << endl;

N
Instantiation
Template Argument
Deduction
string s1("abc"), s2("def");
Example
cout << "s1 = " << s1 << ", s2 = " << s2 << endl;
typename
Swap(s1, s2);
Module Summary cout << "s1 = " << s1 << ", s2 = " << s2 << endl;
}

• The traits of type variable T include


default constructor (T::T()) and
copy assignment operator (T operator=(const T&))
• Our template function cannot be called swap, as std namespace has such a function

Programming in Modern C++ Partha Pratim Das M38.20


typename

Module M38

L
Partha Pratim
Das

E
Objectives &
Outlines

T
What is a
Template?

P
Function
Template
Definition

N
Instantiation
Template Argument
Deduction
Example

typename

Module Summary
typename

Programming in Modern C++ Partha Pratim Das M38.21


typename Keyword

Module M38
• Consider:

L
Partha Pratim
Das template <class T> f (T x) {
T::name * p;

E
Objectives &
Outlines
}

T
What is a
Template?
• What does it mean?

P
Function
Template ◦ T::name is a type and p is a pointer to that type
Definition
◦ T::name and p are variables and this is a multiplication

N
Instantiation
Template Argument
Deduction • To resolve, we use keyword typename:
Example

typename
template <class T> f (T x) { T::name * p; } // Multiplication
Module Summary
template <class T> f (T x) { typename T::name * p; } // Type
• The keywords class and typename have almost the same meaning in a template
parameter
• typename is also used to tell the compiler that an expression is a type expression
Programming in Modern C++ Partha Pratim Das M38.22
Module Summary

Module M38

• Introduced the templates in C++

L
Partha Pratim
Das
• Discussed function templates as generic algorithmic solution for code reuse

E
Objectives &
Outlines • Explained templates argument deduction for implicit instantiation

T
What is a
Template? • Illustrated with examples

P
Function
Template
Definition

N
Instantiation
Template Argument
Deduction
Example

typename

Module Summary

Programming in Modern C++ Partha Pratim Das M38.23


Module M39

L
Partha Pratim
Das
Programming in Modern C++

E
Objectives &
Outlines
Module M39: Template (Class Template): Part 2

T
What is a
Template?

P
Function
Template

Class Template Partha Pratim Das

N
Definition
Instantiation
Partial Template Department of Computer Science and Engineering
Instantiation &
Default Template Indian Institute of Technology, Kharagpur
Parameters
Inheritance
[email protected]
Module Summary

All url’s in this module have been accessed in September, 2021 and found to be functional

Programming in Modern C++ Partha Pratim Das M39.1


Module Recap

Module M39

• Introduced the templates in C++

L
Partha Pratim
Das
• Discussed function templates as generic algorithmic solution for code reuse

E
Objectives &
Outlines • Explained templates argument deduction for implicit instantiation

T
What is a
Template? • Illustrated with examples

P
Function
Template

Class Template

N
Definition
Instantiation
Partial Template
Instantiation &
Default Template
Parameters
Inheritance

Module Summary

Programming in Modern C++ Partha Pratim Das M39.2


Module Objectives

Module M39

• Understand Templates in C++

L
Partha Pratim
Das
• Understand Class Templates

E
Objectives &
Outlines

T
What is a
Template?

P
Function
Template

Class Template

N
Definition
Instantiation
Partial Template
Instantiation &
Default Template
Parameters
Inheritance

Module Summary

Programming in Modern C++ Partha Pratim Das M39.3


Module Outline

Module M39

L
Partha Pratim
Das 1 What is a Template?

E
Objectives &
Outlines

T
What is a 2 Function Template
Template?

P
Function
Template

Class Template
3 Class Template

N
Definition Definition
Instantiation
Partial Template Instantiation
Instantiation &
Default Template
Parameters
Partial Template Instantiation & Default Template Parameters
Inheritance Inheritance
Module Summary

4 Module Summary

Programming in Modern C++ Partha Pratim Das M39.4


What is a Template?

Module M39

L
Partha Pratim
Das

E
Objectives &
Outlines

T
What is a
Template?

P
Function
Template

Class Template

N
Definition
Instantiation
Partial Template
Instantiation &
Default Template
Parameters
Inheritance

Module Summary
What is a Template?

Programming in Modern C++ Partha Pratim Das M39.5


What is a Template?:
RECAP (Module 38)
Module M39

• Templates are specifications of a collection of functions or classes which are

L
Partha Pratim
Das
parameterized by types

E
Objectives &
Outlines • Examples:

T
What is a
Template?
◦ Function search, min etc.
. The basic algorithms in these functions are the same independent of types

P
Function
Template
. Yet, we need to write different versions of these functions for strong type
Class Template

N
Definition checking in C++
Instantiation
Partial Template ◦ Classes list, queue etc.
Instantiation &
Default Template
Parameters
. The data members and the methods are almost the same for list of numbers, list
Inheritance of objects
Module Summary
. Yet, we need to define different classes

Programming in Modern C++ Partha Pratim Das M39.6


Function Template

Module M39

L
Partha Pratim
Das

E
Objectives &
Outlines

T
What is a
Template?

P
Function
Template

Class Template

N
Definition
Instantiation
Partial Template
Instantiation &
Default Template
Parameters
Inheritance

Module Summary
Function Template

Programming in Modern C++ Partha Pratim Das M39.7


Function Template: Code reuse in Algorithms: RECAP (Module 38

Module M39 • We need to compute the maximum of two values that can be of:
◦ int

L
Partha Pratim
Das
◦ double

E
Objectives &
Outlines ◦ char * (C-String)
◦ Complex (user-defined class for complex numbers)

T
What is a
Template?
◦ ...

P
Function
Template • We can do this with overloaded Max functions:
Class Template

N
Definition int Max(int x, int y);
Instantiation double Max(double x, double y);
Partial Template char *Max(char *x, char *y);
Instantiation &
Default Template
Complex Max(Complex x, Complex y);
Parameters
Inheritance
With every new type, we need to add an overloaded function in the library!
Module Summary
• Issues in Max function
◦ Same algorithm (compare two values using the appropriate operator of the type and return
the larger value)
◦ Different code versions of these functions for strong type checking in C++
Programming in Modern C++ Partha Pratim Das M39.8
Class Template

Module M39

L
Partha Pratim
Das

E
Objectives &
Outlines

T
What is a
Template?

P
Function
Template

Class Template

N
Definition
Instantiation
Partial Template
Instantiation &
Default Template
Parameters
Inheritance

Module Summary
Class Template

Programming in Modern C++ Partha Pratim Das M39.9


Class Template: Code Reuse in Data Structure

Module M39
• Solution of several problems needs stack (LIFO)

L
Partha Pratim
Das ◦ Reverse string (char)
◦ Convert infix expression to postfix (char)

E
Objectives &
Outlines ◦ Evaluate postfix expression (int / double / Complex ...)
◦ Depth-first traversal (Node *)

T
What is a
Template? ◦ ...

P
Function
Template
• Solution of several problems needs queue (FIFO)
Class Template ◦ Task Scheduling (Task *)

N
Definition ◦ Process Scheduling (Process *)
Instantiation ◦ ...
Partial Template
Instantiation &
Default Template
• Solution of several problems needs list (ordered)
Parameters
◦ Implementing stack, queue (int / char / ...)
Inheritance
◦ Implementing object collections (UDT)
Module Summary
◦ ...
• Solution of several problems needs ...
• Issues in Data Structure
◦ Data Structures are generic - same interface, same algorithms
◦ C++ implementations are different due to element type
Programming in Modern C++ Partha Pratim Das M39.10
Stack of char and int

Module M39
class Stack { class Stack {
char data_[100]; // Has type char int data_[100]; // Has type int

L
Partha Pratim
Das int top_; int top_;
public: public:

E
Objectives & Stack() :top_(-1) { } Stack() :top_(-1) { }
Outlines
~Stack() { } ~Stack() { }

T
What is a
Template?
void push(const char& item) // Has type char void push(const int& item) // Has type int
{ data_[++top_] = item; } { data_[++top_] = item; }

P
Function
Template

Class Template void pop() void pop()

N
Definition { --top_; } { --top_; }
Instantiation
Partial Template const char& top() const // Has type char const int& top() const // Has type int
Instantiation &
Default Template { return data_[top_]; } { return data_[top_]; }
Parameters
Inheritance
bool empty() const bool empty() const
Module Summary { return top_ == -1; } { return top_ == -1; }
}; };

• Stack of char • Stack of int


• Can we combine these Stack codes using a type variable T?

Programming in Modern C++ Partha Pratim Das M39.11


Class Template

Module M39
• A class template

L
Partha Pratim
Das ◦ describes how a class should be built
◦ supplies the class description and the definition of the member functions using some

E
Objectives &
Outlines arbitrary type name, (as a place holder)

T
What is a
Template?
◦ is a:
. parameterized type with

P
Function
Template

Class Template
. parameterized member functions

N
Definition ◦ can be considered the definition for a unbounded set of class types
Instantiation
Partial Template ◦ is identified by the keyword template
Instantiation &
Default Template
Parameters
. followed by comma-separated list of parameter identifiers (each preceded by
Inheritance
keyword class or keyword typename)
Module Summary
. enclosed between < and > delimiters
. followed by the definition of the class
◦ is often used for container classes
◦ Note that every template parameter is a built-in type or class – type parameters
Programming in Modern C++ Partha Pratim Das M39.12
Stack as a Class Template: Stack.h

Module M39 template<class T>


class Stack {

L
Partha Pratim
Das T data_[100];
int top_;

E
Objectives & public:
Outlines
Stack() :top_(-1) { }

T
What is a ~Stack() { }
Template?
void push(const T& item) { data_[++top_] = item; }

P
Function
Template

Class Template void pop() { --top_; }

N
Definition
Instantiation const T& top() const { return data_[top_]; }
Partial Template
Instantiation &
Default Template
bool empty() const { return top_ == -1; }
Parameters };
Inheritance

Module Summary • Stack of type variable T


• The traits of type variable T include
copy assignment operator (T operator=(const T&))
• We do not call our template class as stack because std namespace has a class stack

Programming in Modern C++ Partha Pratim Das M39.13


Reverse String: Using Stack template

Module M39 #include <iostream>


#include <cstring>

L
Partha Pratim
Das using namespace std;

E
Objectives & #include "Stack.h"
Outlines

T
What is a int main() {
Template? char str[10] = "ABCDE";

P
Function
Template Stack<char> s; // Instantiated for char
Class Template

N
Definition for (unsigned int i = 0; i < strlen(str); ++i)
Instantiation s.push(str[i]);
Partial Template
Instantiation &
Default Template
cout << "Reversed String: ";
Parameters while (!s.empty()) {
Inheritance cout << s.top();
Module Summary s.pop();
}

return 0;
}

• Stack of type char


Programming in Modern C++ Partha Pratim Das M39.14
Postfix Expression Evaluation: Using Stack template
#include <iostream>
Module M39
#include "Stack.h"
using namespace std;

L
Partha Pratim
Das
int main() { // Postfix expression: 1 2 3 * + 9 -

E
Objectives &
Outlines
unsigned int postfix[] = { ’1’, ’2’, ’3’, ’*’, ’+’, ’9’, ’-’ }, ch;

T
What is a Stack<int> s; // Instantiated for int
Template?

P
Function for (unsigned int i = 0; i < sizeof(postfix) / sizeof(unsigned int); ++i) {
Template
ch = postfix[i];
Class Template if (isdigit(ch)) { s.push(ch - ’0’); }

N
Definition else {
Instantiation int op1 = s.top(); s.pop();
Partial Template int op2 = s.top(); s.pop();
Instantiation &
Default Template switch (ch) {
Parameters
case ’*’: s.push(op2 * op1); break;
Inheritance
case ’/’: s.push(op2 / op1); break;
Module Summary case ’+’: s.push(op2 + op1); break;
case ’-’: s.push(op2 - op1); break;
}
}
}
cout << "\n Evaluation " << s.top();
}
Programming in Modern C++ Partha Pratim Das M39.15
Template Parameter Traits

Module M39

• Parameter Types

L
Partha Pratim
Das
◦ may be of any type (including user defined types)

E
Objectives &
Outlines ◦ may be parameterized types, (that is, templates)
◦ MUST support the methods used by the template functions:

T
What is a
Template?
. What are the required constructors?

P
Function
Template . The required operator functions?
Class Template
. What are the necessary defining operations?

N
Definition
Instantiation
Partial Template
Instantiation &
Default Template
Parameters
Inheritance

Module Summary

Programming in Modern C++ Partha Pratim Das M39.16


Function Template Instantiation: RECAP (Module 38)

Module M39
• Each item in the template parameter list is a template argument

L
Partha Pratim
Das
• When a template function is invoked, the values of the template arguments are determined by seeing
the types of the function arguments

E
Objectives &
Outlines template<class T> T Max(T x, T y);

T
What is a template<> char *Max<char *>(char *x, char *y);
Template? template <class T, int size> T Max(T x[size]);

P
Function
Template int a, b; Max(a, b); // Binds to Max<int>(int, int);
Class Template
double c, d; Max(c, d); // Binds to Max<double>(double, double);

N
Definition
char *s1, *s2; Max(s1, s2); // Binds to Max<char*>(char*, char*);
Instantiation
Partial Template int pval[9]; Max<int, 7>(arr); // Binds to Max<int, n>(int[]);
Instantiation &
Default Template
Parameters
• Three kinds of conversions are allowed
Inheritance
◦ L-value transformation (for example, Array-to-pointer conversion)
Module Summary ◦ Qualification conversion
◦ Conversion to a base class instantiation from a class template
• If the same template parameter are found for more than one function argument, template argument
deduction from each function argument must be the same

Programming in Modern C++ Partha Pratim Das M39.17


Class Template Instantiation

Module M39

• Class Template is instantiated only when it is required:

L
Partha Pratim
Das
◦ template<class T> class Stack; // Is a forward declaration

E
Objectives &
Outlines ◦ Stack<char> s; // Is an error
◦ Stack<char> *ps; // Is okay

T
What is a
Template?
◦ void ReverseString(Stack<char>& s, char *str); Is okay

P
Function
Template
• Class template is instantiated before
Class Template

N
Definition ◦ An object is defined with class template instantiation
Instantiation
Partial Template
◦ If a pointer or a reference is dereferenced (for example, a method is invoked)
Instantiation &
Default Template
Parameters
• A template definition can refer to a class template or its instances but a non-template
Inheritance can only refer to template instances
Module Summary

Programming in Modern C++ Partha Pratim Das M39.18


Class Template Instantiation Example
#include <iostream>
Module M39
#include <cstring>
using namespace std;

L
Partha Pratim
Das template<class T> class Stack; // Forward declaration
void ReverseString(Stack<char>& s, char *str); // Stack template definition is not needed

E
Objectives &
Outlines
template<class T> // Definition

T
What is a class Stack { T data_[100]; int top_;
Template?
public: Stack() :top_(-1) { } ~Stack() { }

P
Function void push(const T& item) { data_[++top_] = item; }
Template
void pop() { --top_; }
Class Template const T& top() const { return data_[top_]; }

N
Definition bool empty() const { return top_ == -1; }
Instantiation };
Partial Template
Instantiation &
int main() { char str[10] = "ABCDE";
Default Template Stack<char> s; // Stack template definition is needed
Parameters
ReverseString(s, str);
Inheritance
}
Module Summary void ReverseString(Stack<char>& s, char *str) { // Stack template definition is needed
for (unsigned int i = 0; i < strlen(str); ++i)
s.push(str[i]);
cout << "Reversed String: ";
while (!s.empty())
{ cout << s.top(); s.pop(); }
}
Programming in Modern C++ Partha Pratim Das M39.19
Partial Template Instantiation and Default Template Parameters
#include <iostream>
Module M39
#include <string>
#include <cstring>

L
Partha Pratim
Das template<class T1 = int, class T2 = string> // Version 1 with default parameters
class Student { T1 roll_; T2 name_;

E
Objectives & public: Student(T1 r, T2 n) : roll_(r), name_(n) { }
Outlines
void Print() const { std::cout << "Version 1: (" << name_ << ", " << roll_ << ")" << std::endl; }

T
What is a };
Template?
template<class T1> // Version 2: Partial Template Specialization
class Student<T1, char *> { T1 roll_; char *name_;

P
Function
Template public: Student(T1 r, char *n) : roll_(r), name_(std::strcpy(new char[std::strlen(n) + 1], n)) { }
Class Template void Print() const { std::cout << "Version 2: (" << name_ << ", " << roll_ << ")" << std::endl; }

N
Definition };
Instantiation int main() {
Partial Template Student<int, string> s1(2, "Ramesh"); s1.Print(); // Version 1: T1 = int, T2 = string
Instantiation &
Default Template Student<int> s2(11, "Shampa"); s2.Print(); // Version 1: T1 = int, defa T2 = string
Parameters Student<> s3(7, "Gagan"); s3.Print(); // Version 1: defa T1 = int, defa T2 = string
Inheritance
Student<string> s4("X9", "Lalita"); s4.Print(); // Version 1: T1 = string, defa T2 = string
Module Summary Student<int, char*> s5(3, "Gouri"); s5.Print(); // Version 2: T1 = int, T2 = char*
}
Version 1: (Ramesh, 2)
Version 1: (Shampa, 11)
Version 1: (Gagan, 7)
Version 1: (Lalita, X9)
Version 2: (Gouri, 3)
Programming in Modern C++ Partha Pratim Das M39.20
Templates and Inheritance: Example (List.h)

Module M39 #ifndef __LIST_H


#define __LIST_H

L
Partha Pratim
Das
#include <vector>

E
Objectives & using namespace std;
Outlines

T
What is a template<class T>
Template? class List {
public:

P
Function
Template void put(const T &val) { items.push_back(val); }
Class Template int length() { return items.size(); } // vector<T>::size()

N
Definition bool find(const T &val) {
Instantiation for (unsigned int i = 0; i < items.size(); ++i)
Partial Template if (items[i] == val) return true; // T must support operator==(). Its trait
Instantiation &
Default Template
return false;
Parameters }
Inheritance private:
Module Summary vector<T> items; // T must support T(), ~T()), T(const t&) or move
}; // Its traits

#endif // __LIST_H

• List is basic container class

Programming in Modern C++ Partha Pratim Das M39.21


Templates and Inheritance: Example (Set.h)
#ifndef __SET_H
Module M39
#define __SET_H
#include "List.h"

L
Partha Pratim
Das
template<class T>

E
Objectives &
Outlines
class Set { public:
Set() { };

T
What is a virtual ~Set() { };
Template?
virtual void add(const T &val);

P
Function int length(); // List<T>::length()
Template
bool find(const T &val); // List<T>::find()
Class Template private:

N
Definition List<T> items; // Container List<T>
Instantiation };
Partial Template template<class T>
Instantiation &
Default Template void Set<T>::add(const T &val) {
Parameters
if (items.find(val)) return; // Don’t allow duplicate
Inheritance
items.put(val);
Module Summary }
template<class T> int Set<T>::length() { return items.length(); }
template<class T> bool Set<T>::find(const T &val) { return items.find(val); }
#endif // __SET_H

• Set is a base class for a set


• Set uses List for container
Programming in Modern C++ Partha Pratim Das M39.22
Templates and Inheritance: Example (BoundSet.h)
#ifndef __BOUND_SET_H
Module M39
#define __BOUND_SET_H

L
Partha Pratim
Das #include "Set.h"

E
Objectives &
Outlines
template<class T>
class BoundSet: public Set<T> {

T
What is a public:
Template?
BoundSet(const T &lower, const T &upper);

P
Function void add(const T &val); // add() overridden to check bounds
Template
private:
Class Template T min;

N
Definition T max;
Instantiation };
Partial Template
Instantiation &
Default Template template<class T> BoundSet<T>::BoundSet(const T &lower, const T &upper): min(lower), max(upper) { }
Parameters
template<class T> void BoundSet<T>::add(const T &val) {
Inheritance
if (find(val)) return; // Set<T>::find()
Module Summary if ((val <= max) && (val >= min)) // T must support operator<=() and operator>=(). Its trait
Set<T>::add(val); // Uses add() from parent class
}
#endif // __BOUND_SET_H

• BoundSet is a specialization of Set


• BoundSet is a set of bounded items
Programming in Modern C++ Partha Pratim Das M39.23
Templates and Inheritance: Example (Bounded Set Application)
#include <iostream>
Module M39
using namespace std;
#include "BoundSet.h"

L
Partha Pratim
Das
int main() {

E
Objectives &
Outlines
BoundSet<int> bsi(3, 21); // Allow values between 3 and 21
Set<int> *setptr = &bsi;

T
What is a
Template?
for (int i = 0; i < 25; i++)

P
Function setptr->add(i); // Set<T>::add(const T&) is virtual
Template

Class Template if (bsi.find(4)) // Within bound

N
Definition cout << "We found an expected value\n";
Instantiation if (!bsi.find(0)) // Outside lower bound
Partial Template cout << "We found NO unexpected value\n";
Instantiation &
Default Template if (!bsi.find(25)) // Outside upper bound
Parameters
cout << "We found NO unexpected value\n";
Inheritance
}
Module Summary
We found an expected value
We found NO unexpected value
We found NO unexpected value

• Uses BoundSet to maintain and search elements

Programming in Modern C++ Partha Pratim Das M39.24


Module Summary

Module M39

• Introduced the templates in C++

L
Partha Pratim
Das
• Discussed class templates as generic solution for data structure reuse

E
Objectives &
Outlines • Explained partial template instantiation and default template parameters

T
What is a
Template? • Demonstrated templates on inheritance hierarchy

P
Function
Template • Illustrated with examples
Class Template

N
Definition
Instantiation
Partial Template
Instantiation &
Default Template
Parameters
Inheritance

Module Summary

Programming in Modern C++ Partha Pratim Das M39.25


Module M40

L
Partha Pratim
Das
Programming in Modern C++

E
Objectives &
Outlines
Module M40: Functors: Function Objects

T
Callable Entities

Function Pointers

P
Replace Switch / IF
Statements
Late Binding
Partha Pratim Das

N
Virtual Function
Callback
qsort
Department of Computer Science and Engineering
Issues
Indian Institute of Technology, Kharagpur
Functors
Basic Functor
[email protected]
Simple Example
Examples from STL
Function Pointer
Functor w/o state
All url’s in this module have been accessed in September, 2021 and found to be functional
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.1


Module Recap

Module M40

• Discussed class templates as generic solution for data structure reuse

L
Partha Pratim
Das
• Explained partial template instantiation and default template parameters

E
Objectives &
Outlines • Demonstrated templates on inheritance hierarchy

T
Callable Entities

Function Pointers
• Illustrated with examples

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.2


Module Objectives

Module M40

• Understand the Function Objects or Functor

L
Partha Pratim
Das
• Study the utility of functor in design, especially in STL

E
Objectives &
Outlines

T
Callable Entities

Function Pointers

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.3


Module Outline

Module M40
1 Callable Entities

L
Partha Pratim
Das
2 Function Pointers

E
Objectives & Replace Switch / IF Statements
Outlines
Late Binding

T
Callable Entities

Function Pointers
Virtual Function

P
Replace Switch / IF
Statements
Callback
Late Binding qsort

N
Virtual Function
Callback
Issues
qsort
Issues
3 Functors in C++
Functors Basic Functor
Basic Functor
Simple Example
Simple Example
Examples from STL Examples from STL
Function Pointer Function Pointer
Functor w/o state
Functor w/ state
Functor without state
Functor with state
Module Summary

4 Module Summary
Programming in Modern C++ Partha Pratim Das M40.4
Callable Entities

Module M40

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Callable Entities

Function Pointers

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Callable Entities
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.5


Callable Entities in C / C++

Module M40

• A Callable Entity is an object that

L
Partha Pratim
Das
◦ Can be called using the function call syntax

E
Objectives &
Outlines ◦ Supports Function Call Operator: operator()

T
Callable Entities • Such objects are often called
Function Pointers
◦ A Function Object or

P
Replace Switch / IF
Statements
Late Binding
◦ A Functor

N
Virtual Function
Callback
qsort
Functors
Issues
Some authors distinguish between Callable Entities, Function Objects and Functors, but we
Functors
Basic Functor
will treat these terminology equivalently depending on the context
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.6


Several Callable Entities C++

Module M40

• Function-like Macros

L
Partha Pratim
Das
• C Functions (Global or in Namespace)

E
Objectives &
Outlines • Member Functions

T
Callable Entities
◦ Static
Function Pointers
◦ Non-Static

P
Replace Switch / IF
Statements
Late Binding • Pointers to Functions

N
Virtual Function
Callback ◦ C Functions
qsort
Issues ◦ Member Functions (static / Non-Static)
Functors
• References to functions: Acts like const pointers to functions
Basic Functor
Simple Example
Examples from STL
• Functors: Objects that define operator()
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.7


Function Pointers

Module M40

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Callable Entities

Function Pointers

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointers
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.8


Function Pointers

Module M40

• Points to the address of a function

L
Partha Pratim
Das
◦ Ordinary C functions

E
Objectives &
Outlines ◦ Static C++ member functions
◦ Non-static C++ member functions

T
Callable Entities

Function Pointers
• Points to a function with a specific signature

P
Replace Switch / IF
Statements
Late Binding
◦ List of Calling Parameter Types

N
Virtual Function
◦ Return-Type
Callback
qsort ◦ Calling Convention
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.9


Function Pointers in C

Module M40 • Define a Function Pointer

L
Partha Pratim int (*pt2Function) (int, char, char);
Das

• Calling Convention

E
Objectives &
Outlines
int DoIt (int a, char b, char c); // __cdecl, __stdcall used in MSVC

T
Callable Entities int DoIt (int a, char b, char c) {
Function Pointers printf ("DoIt\n");

P
Replace Switch / IF return a+b+c;
Statements
}
Late Binding
• Assign Address to a Function Pointer

N
Virtual Function
Callback pt2Function = &DoIt; // OR
qsort pt2Function = DoIt;
Issues
• Compare Function Pointers
Functors
Basic Functor if (pt2Function == &DoIt) {
Simple Example printf ("pointer points to DoIt\n");
Examples from STL }
Function Pointer
Functor w/o state
Functor w/ state • Call the Function pointed by the Function Pointer
Module Summary int result = (*pt2Function) (12, ’a’, ’b’);

Programming in Modern C++ Partha Pratim Das M40.10


Function Pointers in C
Direct Function Pointer Using typedef
Module M40

#include <stdio.h> #include <stdio.h>

L
Partha Pratim
Das
int (*pt2Function) (int, char, char); typedef int (*pt2Function) (int, char, char);

E
Objectives & int DoIt (int a, char b, char c); int DoIt (int a, char b, char c);
Outlines

T
Callable Entities int main() { int main() {
Function Pointers pt2Function = DoIt; // &DoIt pt2Function f = &DoIt; // DoIt

P
Replace Switch / IF
Statements int result = (*pt2Function)(12, ’a’, ’b’); int result = f(12, ’a’, ’b’);
Late Binding

N
Virtual Function
printf("%d", result); printf("%d", result);
Callback
qsort
Issues
return 0; return 0;
} }
Functors int DoIt (int a, char b, char c) { int DoIt (int a, char b, char c) {
Basic Functor
printf ("DoIt\n"); printf ("DoIt\n");
Simple Example
Examples from STL
return a + b + c; return a + b + c;
Function Pointer
Functor w/o state
} }
Functor w/ state
DoIt DoIt
Module Summary 207 207

Programming in Modern C++ Partha Pratim Das M40.11


Function Reference In C++

Module M40 • Define a Function Pointer

L
Partha Pratim int (A::*pt2Member)(float, char, char);
Das

• Calling Convention

E
Objectives &
Outlines
class A {

T
Callable Entities
int DoIt (float a, char b, char c) {
Function Pointers cout << "A::DoIt" << endl; return a+b+c; }

P
Replace Switch / IF };
Statements
Late Binding

• Assign Address to a Function Pointer

N
Virtual Function
Callback
qsort pt2Member = &A::DoIt;
Issues

Functors • Compare Function Pointers


Basic Functor
Simple Example
if (pt2Member == &A::DoIt) {
Examples from STL cout <<"pointer points to A::DoIt" << endl;
Function Pointer }
Functor w/o state
Functor w/ state
• Call the Function pointed by the Function Pointer
Module Summary
int result = (*this.*pt2Member)(12, ’a’, ’b’);
Programming in Modern C++ Partha Pratim Das M40.12
Function Pointer: Operations and Programming Techniques

Module M40

• Operations

L
Partha Pratim
Das
◦ Assign an Address to a Function Pointer

E
Objectives &
Outlines ◦ Compare two Function Pointers
◦ Call a Function using a Function Pointer

T
Callable Entities

Function Pointers ◦ Pass a Function Pointer as an Argument

P
Replace Switch / IF
Statements ◦ Return a Function Pointer
Late Binding
◦ Arrays of Function Pointers

N
Virtual Function
Callback
qsort
• Programming Techniques
Issues
◦ Replacing switch/if-statements
Functors
Basic Functor
◦ Realizing user-defined late-binding, or
Simple Example
Examples from STL
. Functions in Dynamically Loaded Libraries
Function Pointer . Virtual Functions
Functor w/o state
Functor w/ state ◦ Implementing callbacks
Module Summary

Programming in Modern C++ Partha Pratim Das M40.13


Function Pointers: Replace Switch/ IF Statements
Solution Using switch Solution Using Function Pointer
Module M40 #include <iostream> #include <iostream>
using namespace std ; using namespace std ;

L
Partha Pratim
Das // The four arithmetic operations // The four arithmetic operations
float Plus(float a, float b) { return a+b ; } float Plus(float a, float b)

E
Objectives & float Minus(float a, float b) { return a-b ; } { return a+b; }
Outlines float Multiply(float a, float b) { return a*b; } float Minus(float a, float b)

T
Callable Entities float Divide(float a, float b) { return a/b ; } { return a-b; }
Function Pointers
void Switch(float a, float b, char opCode) { float Multiply(float a, float b)
float result; { return a*b; }

P
Replace Switch / IF
Statements switch (opCode) { // execute operation float Divide(float a, float b)
Late Binding case ’+’: result = Plus(a, b); break; { return a/b; }

N
Virtual Function case ’-’: result = Minus(a, b); break; // Solution with Function pointer
Callback case ’*’: result = Multiply(a, b); break; void Switch (float a, float b,
qsort
case ’/’: result = Divide(a, b); break; float (*pt2Func)(float, float)) {
Issues
} float result = pt2Func(a, b);
Functors cout << "Result of = "<< result << endl; cout << "Result := " << result << endl;
Basic Functor } }
Simple Example int main() { float a = 10.5, b = 2.5 ; int main() { float a = 10.5, b = 2.5 ;
Examples from STL
Switch(a, b, ’+’); Switch(a, b, &Plus);
Function Pointer
Switch(a, b, ’-’); Switch(a, b, &Minus);
Functor w/o state
Switch(a, b, ’*’); Switch(a, b, &Multiply);
Functor w/ state
Switch(a, b, ’/’); Switch(a, b, &Divide);
Module Summary return 0; return 0;
} }
Programming in Modern C++ Partha Pratim Das M40.14
Function Pointers: Late Binding / Dynamically Loaded Library

Module M40
• A C Feature in Shared Dynamically Loaded Libraries

L
Partha Pratim
Das Program Part-1 Program Part-2

E
Objectives &
Outlines #include <dlfcn.h> #include <iostream>
int main() {

T
Callable Entities using namespace std;
Function Pointers
void* handle = dlopen("hello.so", RTLD_LAZY);
typedef void (*hello_t)(); extern "C" void hello() {

P
Replace Switch / IF
Statements
Late Binding
cout << "hello" << endl;
hello_t myHello = 0; }

N
Virtual Function
Callback myHello = (hello_t)dlsym(handle, "hello");
qsort myHello();
Issues

Functors
dlclose(handle);
Basic Functor
Simple Example
}
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.15


Function Pointers: Late Binding / Virtual Function

Module M40
• A C++ Feature for Polymorphic Member Functions

L
Partha Pratim
Das Code Snippet Part-1 Code Snippet Part-2

E
Objectives &
Outlines class A { int main() {

T
Callable Entities public: A a;
Function Pointers
void f(); B b;

P
Replace Switch / IF virtual void g(); A *p = &b;
Statements
Late Binding
};
a.f(); // A::f()

N
Virtual Function
Callback class B: public A { a.g(); // A::g()
qsort
public: p->f(); // A::f()
Issues
void f(); p->g(); // B::g()
Functors
Basic Functor
virtual void g(); }
Simple Example };
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.16


Example: Callback, Function Pointers

Module M40

• It is a Common C Feature

L
Partha Pratim
Das
// Application

E
Objectives &
Outlines extern void (*func)();
void f() { }

T
Callable Entities

Function Pointers int main() {

P
Replace Switch / IF
Statements func = &f;
Late Binding
g();

N
Virtual Function
Callback }
qsort
Issues

Functors // Library
Basic Functor
Simple Example
void (*func)();
Examples from STL
void g() {
Function Pointer
Functor w/o state (*func)();
Functor w/ state
}
Module Summary

Programming in Modern C++ Partha Pratim Das M40.17


Function Pointers: Callback Illustration (Step 1)

Module M40

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Callable Entities

Function Pointers

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.18


Function Pointers: Callback Illustration (Step 2)

Module M40

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Callable Entities

Function Pointers

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.19


Function Pointers: Callback Illustration (Step 3)

Module M40

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Callable Entities

Function Pointers

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.20


Function Pointers: Callback Illustration (Step 4)

Module M40

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Callable Entities

Function Pointers

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.21


Function Pointers: Callback Illustration (Step-Final)

Module M40

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Callable Entities

Function Pointers

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.22


Function Pointers: Callback Illustration: Whole Process

Module M40

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Callable Entities

Function Pointers

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.23


Function Pointers: Callback: qsort to Quick Sort

Module M40 void qsort(void *base, // Pointer to the first element of the array to be sorted
size_t nitems, // Number of elements in the array pointed by base

L
Partha Pratim
Das size_t size, // Size in bytes of each element in the array
int (*compar)(const void *, const void*)); // Function that compares two elements

E
Objectives &
Outlines
int CmpFunc(const void* a, const void* b) { // Compare function for int

T
Callable Entities

Function Pointers
int ret = (*(const int*)a > *(const int*) b)? 1:
(*(const int*)a == *(const int*) b)? 0: -1;

P
Replace Switch / IF
Statements
return ret;
Late Binding
}

N
Virtual Function
Callback
qsort int main() {
Issues
int field[10];
Functors
Basic Functor
Simple Example
for(int c = 10; c>0; c--)
Examples from STL field[10-c] = c;
Function Pointer
Functor w/o state
Functor w/ state
qsort((void*) field, 10, sizeof(field[0]), CmpFunc);
}
Module Summary

Programming in Modern C++ Partha Pratim Das M40.24


Function Pointers: Issues

Module M40

• No value semantics

L
Partha Pratim
Das
• Weak type checking

E
Objectives &
Outlines • Two function pointers having identical signature are necessarily indistinguishable

T
Callable Entities

Function Pointers
• No encapsulation for parameters

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.25


Functors in C++

Module M40

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Callable Entities

Function Pointers

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Functors in C++
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.26


Functors or Function Objects

Module M40
• Smart Functions

L
Partha Pratim
Das ◦ Functors are functions with a state
◦ Functors encapsulate C / C++ function pointers

E
Objectives &
Outlines
. Uses templates and

T
Callable Entities
. Engages polymorphism
Function Pointers

P
Replace Switch / IF
Statements
• Has its own Type
Late Binding
◦ A class with zero or more private members to store the state and an overloaded

N
Virtual Function
Callback operator() to execute the function
qsort
Issues • Usually faster than ordinary Functions
Functors
Basic Functor
• Can be used to implement callbacks
Simple Example
Examples from STL
• Provides the basis for Command Design Pattern
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.27


Basic Functor

Module M40

• Any class that overloads the function call operator:

L
Partha Pratim
Das
◦ void operator()();

E
Objectives &
Outlines ◦ int operator()(int, int);
◦ double operator()(int, double);

T
Callable Entities

Function Pointers ◦ ...

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.28


Functors: Simple Example

Module M40
• Consider the code below

L
Partha Pratim
Das
int AdderFunction(int a, int b) { // A function
return a + b;

E
Objectives & }
Outlines

T
Callable Entities
class AdderFunctor {
Function Pointers public:

P
Replace Switch / IF
Statements int operator()(int a, int b) { // A functor
Late Binding return a + b;

N
Virtual Function
}
Callback
qsort };
Issues

Functors int main() {


Basic Functor int x = 5;
Simple Example
int y = 7;
Examples from STL
Function Pointer
int z = AdderFunction(x, y); // Function invocation
Functor w/o state
Functor w/ state
AdderFunctor aF;
Module Summary int w = aF(x, y); // aF.operator()(x, y); -- Functor invocation
}
Programming in Modern C++ Partha Pratim Das M40.29
Functors: Examples from STL: Function Pointer for Functor

Module M40 • Fill a vector with random numbers


◦ generate algorithm

L
Partha Pratim
Das #include <algorithm>
template <class ForwardIterator, class Generator>

E
Objectives & void generate(ForwardIterator first, ForwardIterator last, Generator gen) {
Outlines
while (first != last) {

T
Callable Entities *first = gen();
Function Pointers ++first;
}

P
Replace Switch / IF
Statements }
Late Binding
. first, last: Iterators are defined for a range in the sequence. ”[” or ”]” means include the element and ”(” or

N
Virtual Function
Callback
”)” means exclude the element. ForwardIterator has a range [first,last) spanning from first element to
qsort the element before the last
Issues . gen: Generator function that is called with no arguments and returns some value of a type convertible to those
pointed by the iterators
Functors
Basic Functor
. This can either be a function pointer or a function object
Simple Example ◦ Function Pointer rand as Function Object
Examples from STL #include <cstdlib>
Function Pointer
Functor w/o state
// int rand (void);
Functor w/ state

Module Summary vector<int> V(100);


generate(V.begin(), V.end(), rand);
Programming in Modern C++ Partha Pratim Das M40.30
Functors: Examples from STL: Functor without a state

Module M40
• Sort a vector of double by magnitude

L
Partha Pratim
Das ◦ sort algorithm
#include <algorithm>

E
Objectives &
Outlines
template <class RandomAccessIterator, class Compare>

T
Callable Entities
void sort (RandomAccessIterator first, // Simple interface
Function Pointers
RandomAccessIterator last, // Difficult to use incorrectly

P
Replace Switch / IF
Statements Compare comp); // Compare Functor
Late Binding
. first, last: RandomAccessIterator has a range [first,last)

N
Virtual Function
Callback
qsort
. RandomAccessIterator shall point to a type for which swap is properly defined and
Issues which is both move-constructible and move-assignable (C++11)
Functors . comp: Binary function that accepts two elements in the range as arguments, and
Basic Functor
Simple Example
returns a value convertible to bool. The value returned indicates whether the element
Examples from STL passed as first argument is considered to go before the second in the specific strict weak
Function Pointer
Functor w/o state
ordering it defines.
Functor w/ state . The function shall not modify any of its arguments
Module Summary . This can either be a function pointer or a function object
Programming in Modern C++ Partha Pratim Das M40.31
Functors: Examples from STL: Functor without a state

Module M40 • Sort a vector of double by magnitude


Using qsort in C with User-defined Function less mag Using sort in C++ with User-defined Functor less mag

L
Partha Pratim
Das
#include <stdlib.h> #include <algorithm>
// Compare Function pointer // Compare Functor

E
Objectives &
Outlines void qsort(void *base, template <class RandomAccessIterator, class Compare>
size_t nitems, void sort (RandomAccessIterator first,

T
Callable Entities
size_t size, RandomAccessIterator last,
Function Pointers int (*compar)(const void *, const void*)) Compare comp);

P
Replace Switch / IF // Complicated interface. Difficult to use correctly // Simple interface. Difficult to use incorrectly
Statements
Late Binding
// Type-unsafe comparison function // Type-safe comparison functor

N
Virtual Function
Callback
// Intricate and error-prone with void* struct less_mag: public
qsort int less_mag(const void* a, const void* b) { binary_function<double, double, bool> {
Issues return (fabs(*(const double*)a) < bool operator()(double x, double y)
fabs(*(const double*)b) ? 1: 0; { return fabs(x) < fabs(y); }
Functors
Basic Functor
} };
Simple Example
Examples from STL
double V[100]; // Capacity = 100 vector<double> V(100);
Function Pointer // 10 elements are filled - needs to be tracked // 10 elements are filled tracked automatically
Functor w/o state
Functor w/ state // Difficult to call // Easy to call
Module Summary
qsort((void*) V, 10, sizeof(V[0]), less_mag); sort(V.begin(), V.end(), less_mag());

Programming in Modern C++ Partha Pratim Das M40.32


Functors: Examples from STL: Functor with a state

Module M40
• Compute the sum of elements in a vector
◦ for each algorithm

L
Partha Pratim
Das #include <algorithm>
template<class InputIterator, class Function>

E
Objectives & Function for_each(InputIterator first, InputIterator last, Function fn) {
Outlines while (first!=last) {

T
Callable Entities fn (*first);
++first;
Function Pointers
}

P
Replace Switch / IF
Statements return fn; // or, since C++11: return move(fn);
Late Binding }

N
Virtual Function . first, last: InputIterator has a range [first,last)
Callback
. fn: Unary function that accepts an element in the range as argument
qsort
. This can either be a function pointer or a move constructible function object (C++11)
Issues
. Its return value, if any, is ignored.
Functors
Basic Functor
◦ User-defined Functor adder with local state
Simple Example struct adder: public unary_function<double, void> { adder() : sum(0) { }
Examples from STL double sum; // Local state
Function Pointer void operator()(double x) { sum += x; }
Functor w/o state };
Functor w/ state vector<double> V;
Module Summary ...
adder result = for_each(V.begin(), V.end(), adder());
cout << "The sum is " << result.sum << endl;
Programming in Modern C++ Partha Pratim Das M40.33
Module Summary

Module M40

• Introduced Function Objects or Functors

L
Partha Pratim
Das
• Illustrated functors with several simple examples and examples from STL

E
Objectives &
Outlines

T
Callable Entities

Function Pointers

P
Replace Switch / IF
Statements
Late Binding

N
Virtual Function
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer
Functor w/o state
Functor w/ state

Module Summary

Programming in Modern C++ Partha Pratim Das M40.34

You might also like