Home  >  Article  >  Backend Development  >  How to use callback functions in C++?

How to use callback functions in C++?

PHPz
PHPzOriginal
2024-04-13 09:24:01749browse

Callback functions in C are implemented through function pointers or lambda expressions: Function pointer: define type void(*CallbackFunction)(int); register callback function: RegisterCallback(callback); call callback function: CallCallbacks(value); Example: The event handling class registers the callback function and triggers the event. Lambda expression: Register callback function: RegisterCallback(std::function823779cb011116433bf22081bdae9ba2 callback); Call callback function: CallCallbacks(value); Example: Get user input and register callback function.

C++ 中如何使用回调函数?

Usage of callback function in C

The callback function allows the function to return control to the caller, and then in some A function that is executed again when the condition is met. This is useful in event-driven programming, where one event may trigger multiple actions.

In C, callback functions can be implemented through function pointers or lambda expressions.

Use function pointers

// 定义一个函数指针类型
typedef void(*CallbackFunction)(int);

// 注册回调函数
void RegisterCallback(CallbackFunction callback) {
  // 将回调函数存储在列表中
  callbackList.push_back(callback);
}

// 调用回调函数
void CallCallbacks(int value) {
  for (auto callback : callbackList) {
    callback(value);
  }
}

// 实战案例:事件处理

// 定义一个事件处理类
class EventHandler {
public:
  void OnEvent() {
    // 调用注册的回调函数
    CallCallbacks(42);
  }
};

// 创建事件处理类实例
EventHandler eventHandler;

// 订阅事件的回调函数
RegisterCallback([](int value) {
  std::cout << "事件处理程序: " << value << std::endl;
});

// 触发事件
eventHandler.OnEvent();

Use lambda expression

Lambda expression was introduced in C 11, which provides a A concise way to define anonymous functions.

// 注册回调函数
void RegisterCallback(std::function<void(int)> callback) {
  // 将回调函数存储在列表中
  callbackList.push_back(callback);
}

// 调用回调函数
void CallCallbacks(int value) {
  for (auto callback : callbackList) {
    callback(value);
  }
}

// 实战案例:用户输入

// 创建一个获取用户输入的函数
std::string GetUserInput() {
  std::string input;
  std::cout << "输入一些文本:" << std::flush;
  std::cin >> input;
  return input;
}

// 订阅获取用户输入后的回调函数
RegisterCallback([](int value) {
  std::cout << "用户输入了:" << GetUserInput() << std::endl;
});

// 获取用户输入
GetUserInput();

The above is the detailed content of How to use callback functions in C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn