fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. //#include "analogmuxdemux.h"
  5. using byte = unsigned char ;
  6. typedef unsigned char byte ; // or a typedef
  7.  
  8. struct AnalogMux
  9. {
  10. int AnalogRead( byte pin )
  11. {
  12. std::cout << "AnalogMux::AnalogRead: pin == " << int(pin) << '\n' ;
  13. // read
  14. return 0 ;
  15. }
  16. };
  17.  
  18. class potentiometer
  19. {
  20. // http://e...content-available-to-author-only...e.com/w/cpp/utility/functional/function
  21. using read_function_t = std::function< int(byte) > ;
  22. //typedef std::function< int(byte) > read_function_t ; // alternate syntax
  23.  
  24. byte pinNum;
  25. read_function_t readFunction ;
  26.  
  27. public:
  28. potentiometer( byte, read_function_t fun );
  29.  
  30. int analogRead(); // analogreads the pot
  31. };
  32.  
  33. potentiometer::potentiometer( byte pin , read_function_t fun )
  34. {
  35. pinNum = pin ;
  36. readFunction = fun ;
  37. }
  38.  
  39. int potentiometer::analogRead()
  40. {
  41. return readFunction(pinNum);
  42. }
  43.  
  44. int non_member_AnalogRead( byte pin )
  45. {
  46. std::cout << "non_member_AnalogRead: pin == " << int(pin) << '\n' ;
  47. // read
  48. return 0 ;
  49. }
  50.  
  51. int main()
  52. {
  53. AnalogMux aMux ; // instantiate a mux
  54.  
  55. potentiometer p1( 1, non_member_AnalogRead ); // attached to pin 1
  56. p1.analogRead() ;
  57.  
  58. // attached to input 4 on aMux
  59. // bind the function to AnalogMux::AnalogRead to be invoked on aMux
  60. // http://e...content-available-to-author-only...e.com/w/cpp/utility/functional/bind
  61. potentiometer p2( 4, std::bind( &AnalogMux::AnalogRead, aMux, std::placeholders::_1 ) ) ;
  62. p2.analogRead() ;
  63. }
  64.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
non_member_AnalogRead: pin == 1
AnalogMux::AnalogRead: pin == 4