Home > Backend Development > C++ > How to Create Generic C Callbacks for Multiple Classes?

How to Create Generic C Callbacks for Multiple Classes?

Mary-Kate Olsen
Release: 2024-12-10 06:31:13
Original
929 people have browsed it

How to Create Generic C   Callbacks for Multiple Classes?

C Callback Using Class Member for Multiple Classes

Problem:

In C , how can you create a generic callback function that works with multiple classes, each with its own callback member function?

Solution:

Originally, a static callback method and a pointer to the instance were used, but this approach can be improved. Here are two alternative solutions:

Using C 11 std::function and std::bind:

  1. Define an event handler that takes a std::function as an argument:
void addHandler(std::function<void(int)> callback);
Copy after login
  1. Bind the callback function to the instance using std::bind:
std::bind(&amp;MyClass::Callback, this, _1)
Copy after login

Using C 11 Lambda Functions:

With lambda functions, you can further simplify the code:

handler->addHandler([](int x) { std::cout << "x is " << x << '\n'; });
Copy after login

The above is the detailed content of How to Create Generic C Callbacks for Multiple Classes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template