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++中,作用域(Scope)和标识符查找(IdentifierLookup)是理解代码行为的重要概念,本文将详细介绍这些规则,并通过实例来说明它们的工作原理,需... 目录作用域标识符查找规则1. 普通查找(Ordinary Lookup)2. 限定查找(Qualif

C/C++ chrono简单使用场景示例详解

《C/C++chrono简单使用场景示例详解》:本文主要介绍C/C++chrono简单使用场景示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友... 目录chrono使用场景举例1 输出格式化字符串chrono使用场景China编程举例1 输出格式化字符串示

C++/类与对象/默认成员函数@构造函数的用法

《C++/类与对象/默认成员函数@构造函数的用法》:本文主要介绍C++/类与对象/默认成员函数@构造函数的用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录名词概念默认成员函数构造函数概念函数特征显示构造函数隐式构造函数总结名词概念默认构造函数:不用传参就可以

C++类和对象之默认成员函数的使用解读

《C++类和对象之默认成员函数的使用解读》:本文主要介绍C++类和对象之默认成员函数的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、默认成员函数有哪些二、各默认成员函数详解默认构造函数析构函数拷贝构造函数拷贝赋值运算符三、默认成员函数的注意事项总结一

C/C++中OpenCV 矩阵运算的实现

《C/C++中OpenCV矩阵运算的实现》本文主要介绍了C/C++中OpenCV矩阵运算的实现,包括基本算术运算(标量与矩阵)、矩阵乘法、转置、逆矩阵、行列式、迹、范数等操作,感兴趣的可以了解一下... 目录矩阵的创建与初始化创建矩阵访问矩阵元素基本的算术运算 ➕➖✖️➗矩阵与标量运算矩阵与矩阵运算 (逐元

C/C++的OpenCV 进行图像梯度提取的几种实现

《C/C++的OpenCV进行图像梯度提取的几种实现》本文主要介绍了C/C++的OpenCV进行图像梯度提取的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录预www.chinasem.cn备知识1. 图像加载与预处理2. Sobel 算子计算 X 和 Y

C/C++和OpenCV实现调用摄像头

《C/C++和OpenCV实现调用摄像头》本文主要介绍了C/C++和OpenCV实现调用摄像头,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录准备工作1. 打开摄像头2. 读取视频帧3. 显示视频帧4. 释放资源5. 获取和设置摄像头属性

c/c++的opencv图像金字塔缩放实现

《c/c++的opencv图像金字塔缩放实现》本文主要介绍了c/c++的opencv图像金字塔缩放实现,通过对原始图像进行连续的下采样或上采样操作,生成一系列不同分辨率的图像,具有一定的参考价值,感兴... 目录图像金字塔简介图像下采样 (cv::pyrDown)图像上采样 (cv::pyrUp)C++ O

c/c++的opencv实现图片膨胀

《c/c++的opencv实现图片膨胀》图像膨胀是形态学操作,通过结构元素扩张亮区填充孔洞、连接断开部分、加粗物体,OpenCV的cv::dilate函数实现该操作,本文就来介绍一下opencv图片... 目录什么是图像膨胀?结构元素 (KerChina编程nel)OpenCV 中的 cv::dilate() 函

C++ RabbitMq消息队列组件详解

《C++RabbitMq消息队列组件详解》:本文主要介绍C++RabbitMq消息队列组件的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. RabbitMq介绍2. 安装RabbitMQ3. 安装 RabbitMQ 的 C++客户端库4. A