fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. void print(int x) {
  5. std::cout << x << std::endl;
  6. }
  7.  
  8. int main() {
  9. int hour_now = 5;
  10. auto get_hour_now = [&]() { return hour_now; };
  11.  
  12. auto f1 = [&get_hour_now]() { print(get_hour_now() + 10); }; // Correct
  13. auto f2 = std::bind(print, get_hour_now() + 10); // Wrong
  14. auto f3 = std::bind(print, std::bind(std::plus<int>(), get_hour_now(), 10)); // Wrong
  15. auto f4 = std::bind(print, std::bind(std::plus<int>(), std::bind(get_hour_now), 10)); // Correct
  16.  
  17. f1();
  18. f2();
  19. f3();
  20. f4();
  21.  
  22. hour_now = 1000;
  23.  
  24. f1(); // 1010
  25. f2(); // 15
  26. f3(); // 15
  27. f4(); // 1010
  28.  
  29. return 0;
  30. }
  31.  
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
15
15
15
15
1010
15
15
1010