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++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

c++中std::placeholders的使用方法

《c++中std::placeholders的使用方法》std::placeholders是C++标准库中的一个工具,用于在函数对象绑定时创建占位符,本文就来详细的介绍一下,具有一定的参考价值,感兴... 目录1. 基本概念2. 使用场景3. 示例示例 1:部分参数绑定示例 2:参数重排序4. 注意事项5.

使用C++将处理后的信号保存为PNG和TIFF格式

《使用C++将处理后的信号保存为PNG和TIFF格式》在信号处理领域,我们常常需要将处理结果以图像的形式保存下来,方便后续分析和展示,C++提供了多种库来处理图像数据,本文将介绍如何使用stb_ima... 目录1. PNG格式保存使用stb_imagephp_write库1.1 安装和包含库1.2 代码解

C++实现封装的顺序表的操作与实践

《C++实现封装的顺序表的操作与实践》在程序设计中,顺序表是一种常见的线性数据结构,通常用于存储具有固定顺序的元素,与链表不同,顺序表中的元素是连续存储的,因此访问速度较快,但插入和删除操作的效率可能... 目录一、顺序表的基本概念二、顺序表类的设计1. 顺序表类的成员变量2. 构造函数和析构函数三、顺序表

使用C++实现单链表的操作与实践

《使用C++实现单链表的操作与实践》在程序设计中,链表是一种常见的数据结构,特别是在动态数据管理、频繁插入和删除元素的场景中,链表相比于数组,具有更高的灵活性和高效性,尤其是在需要频繁修改数据结构的应... 目录一、单链表的基本概念二、单链表类的设计1. 节点的定义2. 链表的类定义三、单链表的操作实现四、

使用C/C++调用libcurl调试消息的方式

《使用C/C++调用libcurl调试消息的方式》在使用C/C++调用libcurl进行HTTP请求时,有时我们需要查看请求的/应答消息的内容(包括请求头和请求体)以方便调试,libcurl提供了多种... 目录1. libcurl 调试工具简介2. 输出请求消息使用 CURLOPT_VERBOSE使用 C

C++实现获取本机MAC地址与IP地址

《C++实现获取本机MAC地址与IP地址》这篇文章主要为大家详细介绍了C++实现获取本机MAC地址与IP地址的两种方式,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 实际工作中,项目上常常需要获取本机的IP地址和MAC地址,在此使用两种方案获取1.MFC中获取IP和MAC地址获取

C/C++通过IP获取局域网网卡MAC地址

《C/C++通过IP获取局域网网卡MAC地址》这篇文章主要为大家详细介绍了C++如何通过Win32API函数SendARP从IP地址获取局域网内网卡的MAC地址,感兴趣的小伙伴可以跟随小编一起学习一下... C/C++通过IP获取局域网网卡MAC地址通过win32 SendARP获取MAC地址代码#i