Function callback modern way to use function pointer

Function callback modern way to use function pointer

Function Pointer

C++ (std::function)

Instances of std::function can store, copy, and invoke any CopyConstructible Callable functions(ie targets)

#include <functional>
class C {
    int n;
public:
    C(int a) : n(a) {}
    void print() {
        cout << n;
    }
};

void f1(int a) {
    cout << a;
}
int main() {
    // Function pointer to function taking int & returning void
    std::function <void(int)> ptr_f1 = f1;
    ptr_f1(3);                                                      //3

    // Pointer to lambda
    std::function <void()> ptr_lambda = []() { f1(42); };
    ptr_lambda();                                                   //42

    C objC(2);
    // Pointer to class member, returning void
    function <void()> ptr_class_mem = [&objC]() { objC.print(); };   //2
    ptr_class_mem();

    // Or Bind the member function to the object instance using std::bind
    function <void()> ptr_class_mem = bind(&C::print, &objC);        //2

    // Pointer to comparison function in C++11
    function <bool(int, int)> ptr_great = greater <int>();
    if (ptr_great (2,1))
        cout << "2 greater than 1\n";                     //output: 2 less than 1
    function <bool(int, int)> ptr_less = less <int>();
    if (ptr_less (1,2))
        cout << "1 less than 2\n";                        //output: 1 less than 2
}        

C Function Pointer

// Pointer to function returning void, accepting void
void fun(){
    cout << "fun";
}
void (*ptr)() = fun;
ptr();

// Pointer to class method
class A {
public:
    typedef int (A::*ptr)();      //1. Declare function pointer to class A method returning int, accepting nothing
    int fun() {
    cout << "fun";
    }
};
int main() {
    A* obj = new A();            //2. Create object
    A::ptr p = &A::test();       //3. Create Function pointer p pointing to test
    (obj->*p)();                 //4. Invoke function using function pointer
}        

Callback Function

A callback is a function that is passed as an argument to another function and is intended to be “called back” at a later time within that other function. In C++, callbacks are often implemented using function pointers, functors, or std::function objects.

#include <iostream>
#include <functional>
using namespace std;

// function that we will use as a callback
void callBack (int x) {
    cout << "fun " << x;
}

// A function that accepts a callback as an argument
// void executeCallback(void (*funcPtr)(int))
void executeCallback (std::function <void(int)> p) {
    p(10);
}

int main() {
    // Pass the callback function
    executeCallback (callBack);
    return 0;
}
/*
fun 10
*/        

Callback vs Function pointer

Function pointer

  • This is low-level mechanism that points to a function
  • Function pointers are more common in C and simpler C++ applications

Callback

  • High-level concept where a function is passed as an argument to be executed later.
  • Callbacks using std::function are preferred in modern C++ because they provide more flexibility and ease of use

To view or add a comment, sign in

More articles by Amit K.

  • Stored Procedures, Functions in Postgresql

    Stored Procedure Stored Procedure User defined functions stored in database which contains set of SQL statements It can…

  • Troubleshooting Nvidia GPU for ML Workload

    Scenario You are a owner/admin of GPU Farm. These GPUs are placed on standalone docker containers.

  • Getting started with OpenGL

    What is OpenGL This is a library for 2D and 3D graphics rendering. It provides API(Application Programming Interface)…

  • Pyunit or Unitest

    Used to test a unit of source code Features: 1. PyUnit is very simple yet very flexible 2.

  • Calling OpenAI APIs from code

    Steps a. Get openAI API Key openaAI API Key b.

    3 Comments
  • FlatList with Example in React Native

    What is FlatList? displays a scrolling list of changing, but similarly structured, data. Unlike the more generic…

  • Create Postgres Database, Tables, Schema using Diesel(ORM) Rust

    What is Diesel Diesel is a ORM(object-relational mapping). ORM is programming technique that connects object-oriented…

  • Location Sharing App System Design (Bump)

    What is Bump Bump is location sharing Mobile App. Install bump on 2 phones(add as friends).

  • Load Balancers & Caches

    What is Load Balancer? Load Balancer evenly distributes incoming traffic/load among webservers/workers that are defined…

  • REST API / Representation State Transfer

    Restful Web Server/Application? Web application that implements HTTP CRUD methods in Restful way. Eg: Twitter, facebook…

Insights from the community

Others also viewed

Explore topics