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+... 目录一、简介二、移除给定位置的元素三、移除与特定键值等价的元素四、移除满足特android定条件的元

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

C++ Sort函数使用场景分析

《C++Sort函数使用场景分析》sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某些场景需要保持相同元素间的相对顺序,可使... 目录C++ Sort函数详解一、sort函数调用的两种方式二、sort函数使用场景三、sort函数排序

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++

C/C++错误信息处理的常见方法及函数

《C/C++错误信息处理的常见方法及函数》C/C++是两种广泛使用的编程语言,特别是在系统编程、嵌入式开发以及高性能计算领域,:本文主要介绍C/C++错误信息处理的常见方法及函数,文中通过代码介绍... 目录前言1. errno 和 perror()示例:2. strerror()示例:3. perror(

C++变换迭代器使用方法小结

《C++变换迭代器使用方法小结》本文主要介绍了C++变换迭代器使用方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、源码2、代码解析代码解析:transform_iterator1. transform_iterat

详解C++中类的大小决定因数

《详解C++中类的大小决定因数》类的大小受多个因素影响,主要包括成员变量、对齐方式、继承关系、虚函数表等,下面就来介绍一下,具有一定的参考价值,感兴趣的可以了解一下... 目录1. 非静态数据成员示例:2. 数据对齐(Padding)示例:3. 虚函数(vtable 指针)示例:4. 继承普通继承虚继承5.

C++中std::distance使用方法示例

《C++中std::distance使用方法示例》std::distance是C++标准库中的一个函数,用于计算两个迭代器之间的距离,本文主要介绍了C++中std::distance使用方法示例,具... 目录语法使用方式解释示例输出:其他说明:总结std::distance&n编程bsp;是 C++ 标准

C++ 中的 if-constexpr语法和作用

《C++中的if-constexpr语法和作用》if-constexpr语法是C++17引入的新语法特性,也被称为常量if表达式或静态if(staticif),:本文主要介绍C++中的if-c... 目录1 if-constexpr 语法1.1 基本语法1.2 扩展说明1.2.1 条件表达式1.2.2 fa

C++中::SHCreateDirectoryEx函数使用方法

《C++中::SHCreateDirectoryEx函数使用方法》::SHCreateDirectoryEx用于创建多级目录,类似于mkdir-p命令,本文主要介绍了C++中::SHCreateDir... 目录1. 函数原型与依赖项2. 基本使用示例示例 1:创建单层目录示例 2:创建多级目录3. 关键注