」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用類成員和“ std :: function”實現通用C ++回調?

如何使用類成員和“ std :: function”實現通用C ++回調?

發佈於2025-03-22
瀏覽:289

How to Implement Generic C   Callbacks Using Class Members and `std::function`?
使用類成員使用通用實現

回調的原始問題旨在創建一個通用事件處理機制,該機制將跨不同類持續工作。與其依靠靜態方法並傳遞class實例指針,不如使用std ::函數和std :: bind。

function :: function

將特定的類方法綁定到事件處理程序,std :: bind使用。 std :: bind指定該指針和触發事件時要調用的函數。

free-stane函數和lambda functions

如果回調是沒有類上下文的免費式函數,則不需要std :: bind。 { // ... } int main() { // ... Handler-> Addhandler(freestandingCallback); }

For anonymous callbacks, lambda functions can be used with the event handler.

handler->addHandler([](int x) { std::cout class EventHandler { public: void addHandler(std::function callback) { cout In this way, using std::function and std::bind provides a flexible以及可以應用於不同類和功能的回調的通用解決方案。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3