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

要查看或添加评论,请登录

Amit K.的更多文章

  • Pyunit or Unitest

    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

    Calling OpenAI APIs from code

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

    3 条评论
  • FlatList with Example in React Native

    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

    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)

    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

    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

    REST API / Representation State Transfer

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

  • Inter Thread Communication in Rust using Channels

    Inter Thread Communication in Rust using Channels

    What is Channel? Sender and Receiver are connected via Channel. They can send/recv data via channel.

  • Slices in Rust

    Slices in Rust

    What is Slice Slice is somepart of larger data, it always borrow data(Hence RO) from the sliced type. It gives you a…

  • Traits in Rust

    Traits in Rust

    What is Triat in Rust Interface/class in Rust(declared with keyword trait) having Virtual Functions(not pure Virtual)…

社区洞察

其他会员也浏览了