×

Single Handling in C++

Introduction:

Single handling in C++ refers to a technique for processing multiple events or requests with a single function or handler rather than creating separate functions for each task. This allows for a more efficient and organized codebase, as well as reducing the amount of code that needs to be written.

Single handling is most commonly used in event-driven programming, where multiple events can occur at any given time and must be processed in a specific order. For example, in GUI programming, events like button clicks, keyboard inputs, and window resizing need to be handled in a way that ensures that the application remains responsive and stable.

In C++, single handling can be achieved using function pointers, function objects, or the Standard Template Library (STL) functions. The choice of implementation depends on the specific requirements of the application. In this article, we will focus on function pointers and function objects, as these are the most commonly used techniques for single handling in C++.

Single handling using function pointers:

Function pointers allow a programmer to pass a function as an argument to another function, which can then be called within the receiving function. This allows for the creation of a single handler that can process multiple events by simply calling the appropriate function based on the type of event received. For example, in GUI programming, a single function can be used to handle button clicks, keyboard inputs, and window resizing events by calling different functions based on the type of event received.

Here is an example of single handling using function pointers in C++:

#include <iostream>


void handleEvent1() {
  std::cout << "Handling Event 1" << std::endl;


}


void handleEvent2() {
  std::cout << "Handling Event 2" << std::endl;
}


void handleEvent(int event, void(*handler)()) {
  switch (event) {
    case 1:
      handler = &handleEvent1;
      break;
    case 2:
      handler = &handleEvent2;
      break;
    default:
      std::cout << "Invalid event" << std::endl;
      return;
  }
  handler();
}


int main() {
  handleEvent(1, &handleEvent1);
  handleEvent(2, &handleEvent2);
  handleEvent(3, &handleEvent2);


  return 0;
}

Explanation:

This program is an example of single handling in C++ using function pointers. The handleEvent function is the single handler that can handle multiple events.

  • The handleEvent function takes two arguments:
  • int event: the type of event to be handled
  • void(*handler)(): a pointer to a function that will handle the event.
  • The handleEvent function uses a switch statement to determine which event is being handled and sets the handler function pointer to the appropriate function (handleEvent1 or handleEvent2) based on the value of event.
  • If event is neither 1 nor 2, the function returns and outputs "Invalid event".
  • In the main function, the handleEvent function is called three times with different values for event.
  • For the first two calls, handleEvent1 and handleEvent2 are passed as the handler argument.
  • For the third call, handleEvent2 is passed as the handler argument even though the event is 3, which is an invalid value.

Program Output:

Single Handling in C++

Single handling using function objects:

Function objects, also known as functors, are objects that can be called like a function. They are helpful for single handling because they can store data, making them useful for cases where the same function needs to be used with different data. For example, a single function object can be used to handle multiple button clicks by storing the data associated with each button in the object and calling the appropriate function when the button is clicked.

Here is an example of single handling using function objects in C++:

#include <iostream>
#include <map>




class EventHandler {
 public:
  void operator()(int event) {
    switch (event) {
      case 1:
        std::cout << "Handling Event 1" << std::endl;
        break;
      case 2:
        std::cout << "Handling Event 2" << std::endl;
        break;
      default:
        std::cout << "Invalid event" << std::endl;
        break;
    }
  }
};


int main() {
  EventHandler handleEvent;
  handleEvent(1);
  handleEvent(2);
  handleEvent(3);


  return 0;
}

Explanation:

This program demonstrates an example of single handling using function objects in C++.

  • The EventHandler class is defined with a single function operator(), which is overloaded to act as a function call operator.
  • This allows instances of the EventHandler class to be used as if they were functions.
  • In the operator() function, a switch statement is used to handle different events.
  • Depending on the value of the event argument, the function will output a message indicating that event 1 or 2 is being handled, or that the event is invalid.
  • In the main function, an instance of the EventHandler class is created with the name handleEvent.
  • This instance is then used to handle three events by calling it with an integer argument, either 1, 2, or 3.

Program Output:

Single Handling in C++

Single handling using STL functions:

The STL functions, such as std::for_each and std::transform, are also useful for single handling in C++. They provide a way to perform operations on various elements, such as an array or a container, without having to write a separate function for each element. This allows for a more concise and efficient codebase, as well as reducing the amount of code that needs to be written.

#include <iostream>
#include <vector>


#include <algorithm>


void handleEvent(int event) {
  switch (event) {
    case 1:
      std::cout << "Handling Event 1" << std::endl;
      break;
    case 2:
      std::cout << "Handling Event 2" << std::endl;
      break;
    default:
      std::cout << "Invalid event" << std::endl;
      break;
  }
}


int main() {
  std::vector<int> events{1, 2, 3};
  std::for_each(events.begin(), events.end(), handleEvent);


  return 0;
}

Explanation:

This program demonstrates the use of the STL function std::for_each to handle multiple events using a single function, handleEvent.

std::for_each is a generic algorithm that applies a function to each element in a range.

  • In this program, the range is defined by events.begin() and events.end(), which represent the start and end of the std::vector events. The function that is applied to each element is handleEvent.
  • The handleEvent function takes an integer argument, event, and processes it based on its value.
  • If event is equal to 1, it outputs "Handling Event 1". If event is equal to 2, it outputs "Handling Event 2". If event is neither 1 nor 2, it outputs "Invalid event".
  • The std::for_each algorithm applies handleEvent to each element in the events vector, processing all events in the vector using a single function.

Program Output:

Single Handling in C++

Related Topics

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

wcscpy(), wcslen(), wcscmp() Functions in C++

There are many built-in functions in C++ programming language which differentiate it from C programming language in most hardware-coded languages. We will now closely look into the applications of three...

4 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

Char Array to String in C++

Regardless of the programming language you use, data structure is critical to the success of your project. Although each programming language has its own collection of data structures, C++ contains a...

4 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.

strcat() vs strncat() in C++

In this tutorial, we will explore about strcat() and strncat() in the most usable language C++. We will also look at the difference between them. strcat() C++ is a computer language with...

4 minutes read.

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

C++ User Defined Exceptions

Overriding and inheriting exception class capabilities may be used to define the new exception. Exception handling can also be used with classes. We may also make an exception for user-defined...

4 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.