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
Mary-Kate OlsenOriginal
2024-12-10 06:31:13884browse

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);
  1. Bind the callback function to the instance using std::bind:
std::bind(&amp;MyClass::Callback, this, _1)

Using C 11 Lambda Functions:

With lambda functions, you can further simplify the code:

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

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!

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