fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <map>
  4. #include <tuple>
  5.  
  6. using namespace std;
  7.  
  8. using tCommandKey=unsigned int;
  9. using tCommandDescription=string;
  10. using tCommandUnit=string;
  11. using tCommandValueConvertor=function<float(int)>;
  12. using tCommandData=tuple<tCommandDescription, tCommandUnit, tCommandValueConvertor>;
  13.  
  14. static const map<tCommandKey, tCommandData> commands = {
  15. { 0x41, make_tuple("weight","g", nullptr) },
  16. { 0x42, make_tuple("voltage", "V", [](int in) { return (float)in / 10; }), }
  17. };
  18.  
  19. int main() {
  20. // your code goes here
  21.  
  22. auto it = commands.find(0x42);
  23. if (it != commands.end())
  24. {
  25. int in = 255;
  26.  
  27. auto [desc, unit, convertor] = it->second;
  28.  
  29. float result = convertor ? convertor(in) : in;
  30. cout << "command addr " << it->first;
  31. cout << " reading " << desc;
  32. cout << " in [" << unit << "]";
  33. cout << ((convertor) ? "with" : "without") << " conversion";
  34. cout << ", result = " << result;
  35. }
  36.  
  37. return 0;
  38. }
Success #stdin #stdout 0s 5684KB
stdin
Standard input is empty
stdout
command addr 66 reading voltage in [V]with conversion, result = 25.5