User Tools

Site Tools


c:c_callback_functions

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
c:c_callback_functions [2021/04/28 08:27] – created peterc:c_callback_functions [2021/04/28 08:34] (current) peter
Line 1: Line 1:
-====== C - C++ Callback functions ======+====== C - C++ Callback functions ======
  
 +===== callback_function.hpp =====
  
-[[C:C++ Callback functions|C++ Callback functions]]+<code cpp> 
 +#pragma once 
 + 
 +#include <string> 
 + 
 +// Define a callback function based on a class method and call it with argument "output"
 +void use_callback_function(std::string output); 
 +</code> 
 + 
 +---- 
 + 
 +===== callback_function.cpp ===== 
 + 
 + 
 +<code cpp> 
 +#include "callback_function.hpp" 
 +#include <string> 
 +#include <iostream> 
 +#include <functional> 
 + 
 + 
 +class MyClass 
 +
 +public: 
 +  static void mystaticfunction(std::string str) 
 +  { 
 +    std::cout << str << std::endl; 
 +  } 
 + 
 + 
 +  void mymemberfunction(std::string str) 
 +  { 
 +    mystaticfunction(str); 
 +  } 
 +}; 
 + 
 + 
 +void test(std::string str, std::function<void(std::string)> callBack = nullptr) 
 +
 +  if (callBack) 
 +  { 
 +    callBack(str); 
 +  } 
 +
 + 
 + 
 +void use_callback_function(std::string output) 
 +
 +  // Sample 1. 
 +  test(output, MyClass::mystaticfunction); 
 + 
 + 
 +  // Sample 2. 
 +  MyClass myClass; 
 +  auto callBack = [&myClass](std::string str) 
 +  { 
 +    myClass.mymemberfunction(str); 
 +  }; 
 +   
 +  test(output, callBack); 
 +
 +</code> 
 + 
 + 
 +---- 
 + 
 +===== References ===== 
 + 
 +https://en.cppreference.com/w/cpp/utility/functional/function
c/c_callback_functions.1619598478.txt.gz · Last modified: 2021/04/28 08:27 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki