Callback in C++

2024-06-20 05:48
文章标签 c++ callback

本文主要是介绍Callback in C++,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Callback in C++

非原创,转载自:
https://stackoverflow.com/questions/2298242/callback-functions-in-c

文章目录

  • Callback in C++
    • 非原创,转载自: https://stackoverflow.com/questions/2298242/callback-functions-in-c
    • @[TOC](文章目录)
  • 1. What are callables in C++(11)
  • 2. Function Pointer
    • 2.1 notation for function pointer
    • 2.2 Callback call notation
    • 2.3 Example
  • 3. Pointer to member function
    • 3.1 Pointer notation
    • 3.2 Callback call notation
    • 3.3 Callback use notation and compatible types
  • 4. std::function objects
    • 4.1 notation
    • 4.2 Callback call notation
    • 4.3 Callback use notation and compatible types
      • 4.3.1 Function pointer and pointer to member function
      • 4.3.2 Lambda expressions
      • 4.3.3 std::bind expression
      • 4.3.4 Function objects
    • Example
  • Extra notes
    • about std::bind
    • about lambda expression

提示:以下是本篇文章正文内容,下面案例可供参考

1. What are callables in C++(11)

Callback functionality can be realized in several ways in C++(11) since several different things turn out to be callable*:

Function pointers (including pointers to member functions)
std::function objects
Lambda expressions
Bind expressions
Function objects (classes with overloaded function call operator operator())

2. Function Pointer

Let’s have a simple function foo first:

int foo (int x) {return x + 2}

2.1 notation for function pointer

basic notation:

return_type (*)(parameter_type_1, parameter_type_2, parameter_type_3)
// i.e. a pointer to foo has the type:
int (*)(int)

with name:

return_type (* name) (parameter_type_1, parameter_type_2, parameter_type_3)// i.e. f_int_t is a type: function pointer taking one int argument, returning int
typedef int (*f_int_t) (int); // foo_p is a pointer to function taking int returning int
// initialized by pointer to function foo taking int returning int
int (* foo_p)(int) = &foo; 
// can alternatively be written as 
f_int_t foo_p = &foo;

instead of typedef, you can also use:

using f_int_t = int(*)(int);

And a declaration of a function using a callback of function pointer type will be:

// foobar having a callback argument named moo of type 
// pointer to function returning int taking int as its argument
int foobar (int x, int (*moo)(int));
// if f_int is the function pointer typedef from above we can also write foobar as:
int foobar (int x, f_int_t moo);

2.2 Callback call notation

The call notation follows simple function call syntax

int foobar (int x, int (*moo)(int))
{return x + moo(x); // function pointer moo called using argument x
}
// analog
int foobar (int x, f_int_t moo)
{return x + moo(x); // function pointer moo called using argument x
}

2.3 Example

A function ca be written that doesn’t rely on how the callback works:

void tranform_every_int(int * v, unsigned n, int (*fp)(int))
{for (unsigned i = 0; i < n; ++i){v[i] = fp(v[i]);}
}

where possible callback could be:

int double_int(int x) { return 2*x; }
int square_int(int x) { return x*x; }

used like

int a[5] = {1, 2, 3, 4, 5};
tranform_every_int(&a[0], 5, double_int);
// now a == {2, 4, 6, 8, 10};
tranform_every_int(&a[0], 5, square_int);
// now a == {4, 16, 36, 64, 100};

3. Pointer to member function

A pointer to member function (of some class C) is a special type of (and even more complex) function pointer which requires an object of type C to operate on.

struct C
{int y;int foo(int x) const { return x+y; }
};

3.1 Pointer notation

A pointer to member function type for some class T has the notation

// can have more or less parameters
return_type (T::*)(parameter_type_1, parameter_type_2, parameter_type_3)
// i.e. a pointer to C::foo has the type
int (C::*) (int)

where a named pointer to member function is like:

return_type (T::* name) (parameter_type_1, parameter_type_2, parameter_type_3)// i.e. a type `f_C_int` representing a pointer to member function of `C`
// taking int returning int is:
typedef int (C::* f_C_int_t) (int x); // The type of C_foo_p is a pointer to member function of C taking int returning int
// Its value is initialized by a pointer to foo of C
int (C::* C_foo_p)(int) = &C::foo;
// which can also be written using the typedef:
f_C_int_t C_foo_p = &C::foo;

when passing as a parameter:

// C_foobar having an argument named moo of type pointer to member function of C
// where the callback returns int taking int as its argument
// also needs an object of type c
int C_foobar (int x, C const &c, int (C::*moo)(int));
// can equivalently declared using the typedef above:
int C_foobar (int x, C const &c, f_C_int_t moo);

3.2 Callback call notation

The pointer to member function of C can be invoked, with respect to an object of type C by using member access operations on the dereferenced pointer. Note: Parenthesis required!

int C_foobar (int x, C const &c, int (C::*moo)(int))
{return x + (c.*moo)(x); // function pointer moo called for object c using argument x
}
// analog
int C_foobar (int x, C const &c, f_C_int_t moo)
{return x + (c.*moo)(x); // function pointer moo called for object c using argument x
}

Note: If a pointer to C is available the syntax is equivalent (where the pointer to C must be dereferenced as well):

int C_foobar_2 (int x, C const * c, int (C::*meow)(int))
{if (!c) return x;// function pointer meow called for object *c using argument xreturn x + ((*c).*meow)(x); 
}
// or equivalent:
int C_foobar_2 (int x, C const * c, int (C::*meow)(int))
{if (!c) return x;// function pointer meow called for object *c using argument xreturn x + (c->*meow)(x); 
}

3.3 Callback use notation and compatible types

A callback function taking a member function pointer of class T can be called using a member function pointer of class T.

C my_c{2}; // aggregate initializationint a = 5;int b = C_foobar(a, my_c, &C::foo); // call C_foobar with pointer to foo as its callback

4. std::function objects

under header ;
The std::function class is a polymorphic function wrapper to store, copy or invoke callables.

4.1 notation

The type of a std::function object storing a callable looks like:

std::function<return_type(parameter_type_1, parameter_type_2, parameter_type_3)>// i.e. using the above function declaration of foo:
std::function<int(int)> stdf_foo = &foo;
// or C::foo:
std::function<int(const C&, int)> stdf_C_foo = &C::foo;

4.2 Callback call notation

The class std::function has operator() defined which can be used to invoke its target.

int stdf_foobar (int x, std::function<int(int)> moo)
{return x + moo(x); // std::function moo called
}
// or 
int stdf_C_foobar (int x, C const &c, std::function<int(C const &, int)> moo)
{return x + moo(c, x); // std::function moo called using c and x
}

4.3 Callback use notation and compatible types

4.3.1 Function pointer and pointer to member function

A function pointer

int a = 2;
int b = stdf_foobar(a, &foo);
// b == 6 ( 2 + (2+2) )

or a pointer to member function

int a = 2;
C my_c{7}; // aggregate initialization
int b = stdf_C_foobar(a, c, &C::foo);
// b == 11 == ( 2 + (7+2) )

4.3.2 Lambda expressions

An unnamed closure from a lambda expression can be stored in a std::function object:

int a = 2;
int c = 3;
int b = stdf_foobar(a, [c](int x) -> int { return 7+c*x; });
// b == 15 ==  a + (7*c*a) == 2 + (7+3*2)

4.3.3 std::bind expression

the result of std::bind is returned as a functional object. like:

int foo_2 (int x, int y) { return 9*x + y; }
using std::placeholders::_1;int a = 2;
int b = stdf_foobar(a, std::bind(foo_2, _1, 3));
// b == 23 == 2 + ( 9*2 + 3 )
int c = stdf_foobar(a, std::bind(foo_2, 5, _1));
// c == 49 == 2 + ( 9*5 + 2 )

Where also objects can be bound as the object for the invocation of pointer to member functions:

int a = 2;
C const my_c{7}; // aggregate initialization
int b = stdf_foobar(a, std::bind(&C::foo, my_c, _1));
// b == 1 == 2 + ( 2 + 7 )

4.3.4 Function objects

Objects of classes having a proper operator() overload can be stored inside a std::function object, as well.

struct Meow
{int y = 0;Meow(int y_) : y(y_) {}int operator()(int x) { return y * x; }
};
int a = 11;
int b = stdf_foobar(a, Meow{8});
// b == 99 == 11 + ( 8 * 11 )

Example

Changing the function pointer example to use std::function

void stdf_tranform_every_int(int * v, unsigned n, std::function<int(int)> fp)
{for (unsigned i = 0; i < n; ++i){v[i] = fp(v[i]);}
}

gives a whole lot more utility to that function because (see 3.3) we have more possibilities to use it:

// using function pointer still possible
int a[5] = {1, 2, 3, 4, 5};
stdf_tranform_every_int(&a[0], 5, double_int);
// now a == {2, 4, 6, 8, 10};// use it without having to write another function by using a lambda
stdf_tranform_every_int(&a[0], 5, [](int x) -> int { return x/2; });
// now a == {1, 2, 3, 4, 5}; again// use std::bind :
int nine_x_and_y (int x, int y) { return 9*x + y; }
using std::placeholders::_1;
// calls nine_x_and_y for every int in a with y being 4 every time
stdf_tranform_every_int(&a[0], 5, std::bind(nine_x_and_y, _1, 4));
// now a == {13, 22, 31, 40, 49};

Extra notes

about std::bind

https://thispointer.com/stdbind-tutorial-and-usage-details/
useful STL:
std::count_if
std::count_if Returns the number of elements in the range [firstValue,lastValue) for which predFunctionObject is true.
std::find_if

about lambda expression

C++ 11 introduced lambda expression to allow us write an inline function which can be used for short snippets of code that are not going to be reuse and not worth naming. In its simplest form lambda expression can be defined as follows:

[ capture clause ] (parameters) -> return-type  
{   definition of method   
} 

Generally return-type in lambda expression are evaluated by compiler itself and we don’t need to specify that explicitly and -> return-type part can be ignored but in some complex case as in conditional statement, compiler can’t make out the return type and we need to specify that.
Various uses of lambda expression with standard function are given below :

// Function to print vector
void printVector(vector<int> v)
{// lambda expression to print vectorfor_each(v.begin(), v.end(), [](int i){std::cout << i << " ";});cout << endl;
}int main()
{vector<int> v {4, 1, 3, 5, 2, 3, 1, 7};printVector(v);// below snippet find first number greater than 4// find_if searches for an element for which// function(third argument) returns truevector<int>:: iterator p = find_if(v.begin(), v.end(), [](int i){return i > 4;});cout << "First number greater than 4 is : " << *p << endl;// function to sort vector, lambda expression is for sorting in// non-increasing order Compiler can make out return type as// bool, but shown here just for explanationsort(v.begin(), v.end(), [](const int& a, const int& b) -> bool{return a > b;});
}

A lambda expression can have more power than an ordinary function by having access to variables from the enclosing scope. We can capture external variables from enclosing scope by three ways :
Capture by reference
Capture by value
Capture by both (mixed capture)
Syntax used for capturing variables :
[&] : capture all external variable by reference
[=] : capture all external variable by value
[a, &b] : capture a by value and b by reference
A lambda with empty capture clause [ ] can access only those variable which are local to it.
Capturing ways are demonstrated below :

// C++ program to demonstrate lambda expression in C++
#include <bits/stdc++.h>
using namespace std;int main()
{vector<int> v1 = {3, 1, 7, 9};vector<int> v2 = {10, 2, 7, 16, 9};// access v1 and v2 by referenceauto pushinto = [&] (int m){v1.push_back(m);v2.push_back(m);};// it pushes 20 in both v1 and v2pushinto(20);// access v1 by copy[v1](){for (auto p = v1.begin(); p != v1.end(); p++){cout << *p << " ";}};int N = 5;// below snippet find first number greater than N// [N] denotes, can access only N by valuevector<int>:: iterator p = find_if(v1.begin(), v1.end(), [N](int i){return i > N;});cout << "First number greater than 5 is : " << *p << endl;// function to count numbers greater than or equal to N// [=] denotes, can access all variableint count_N = count_if(v1.begin(), v1.end(), [=](int a){return (a >= N);});cout << "The number of elements greater than or equal to 5 is : "<< count_N << endl;
}

这篇关于Callback in C++的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1077279

相关文章

【C++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<

C++包装器

包装器 在 C++ 中,“包装器”通常指的是一种设计模式或编程技巧,用于封装其他代码或对象,使其更易于使用、管理或扩展。包装器的概念在编程中非常普遍,可以用于函数、类、库等多个方面。下面是几个常见的 “包装器” 类型: 1. 函数包装器 函数包装器用于封装一个或多个函数,使其接口更统一或更便于调用。例如,std::function 是一个通用的函数包装器,它可以存储任意可调用对象(函数、函数

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

06 C++Lambda表达式

lambda表达式的定义 没有显式模版形参的lambda表达式 [捕获] 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 有显式模版形参的lambda表达式 [捕获] <模版形参> 模版约束 前属性 (形参列表) 说明符 异常 后属性 尾随类型 约束 {函数体} 含义 捕获:包含零个或者多个捕获符的逗号分隔列表 模板形参:用于泛型lambda提供个模板形参的名

6.1.数据结构-c/c++堆详解下篇(堆排序,TopK问题)

上篇:6.1.数据结构-c/c++模拟实现堆上篇(向下,上调整算法,建堆,增删数据)-CSDN博客 本章重点 1.使用堆来完成堆排序 2.使用堆解决TopK问题 目录 一.堆排序 1.1 思路 1.2 代码 1.3 简单测试 二.TopK问题 2.1 思路(求最小): 2.2 C语言代码(手写堆) 2.3 C++代码(使用优先级队列 priority_queue)

【C++高阶】C++类型转换全攻略:深入理解并高效应用

📝个人主页🌹:Eternity._ ⏩收录专栏⏪:C++ “ 登神长阶 ” 🤡往期回顾🤡:C++ 智能指针 🌹🌹期待您的关注 🌹🌹 ❀C++的类型转换 📒1. C语言中的类型转换📚2. C++强制类型转换⛰️static_cast🌞reinterpret_cast⭐const_cast🍁dynamic_cast 📜3. C++强制类型转换的原因📝

C++——stack、queue的实现及deque的介绍

目录 1.stack与queue的实现 1.1stack的实现  1.2 queue的实现 2.重温vector、list、stack、queue的介绍 2.1 STL标准库中stack和queue的底层结构  3.deque的简单介绍 3.1为什么选择deque作为stack和queue的底层默认容器  3.2 STL中对stack与queue的模拟实现 ①stack模拟实现

c++的初始化列表与const成员

初始化列表与const成员 const成员 使用const修饰的类、结构、联合的成员变量,在类对象创建完成前一定要初始化。 不能在构造函数中初始化const成员,因为执行构造函数时,类对象已经创建完成,只有类对象创建完成才能调用成员函数,构造函数虽然特殊但也是成员函数。 在定义const成员时进行初始化,该语法只有在C11语法标准下才支持。 初始化列表 在构造函数小括号后面,主要用于给

2024/9/8 c++ smart

1.通过自己编写的class来实现unique_ptr指针的功能 #include <iostream> using namespace std; template<class T> class unique_ptr { public:         //无参构造函数         unique_ptr();         //有参构造函数         unique_ptr(