fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template<typename Fn>
  5. void call_value(Fn f) { f(); }
  6. template<typename Fn>
  7. void call_ref(Fn & f) { f(); }
  8. template<typename Fn>
  9. void call_cref(Fn const & f) { f(); }
  10.  
  11. struct Data {
  12. Data() {}
  13. Data(Data const &) {
  14. cout << "copy" << endl;
  15. }
  16. Data(Data &&) {
  17. cout << "move" << endl;
  18. }
  19. };
  20.  
  21. int main(int, char **) {
  22. Data data;
  23.  
  24. auto capref = [&data] () {};
  25. cout << "capture by value, so we get a ";
  26. auto capcp = [data] () {};
  27.  
  28. cout << " the lambda with a reference ... ";
  29. call_value(capref);
  30. cout << " could now be called and mutate .. ";
  31. call_ref(capref);
  32. call_cref(capref);
  33. cout << " but won't, as it had to be declared mutable " << endl;
  34.  
  35. cout << "the lambda with an instance: ";
  36. call_value(capcp);
  37. cout << "but not ";
  38. call_ref(capcp);
  39. call_cref(capcp);
  40. cout << " the reference versions " << endl;
  41.  
  42. bool en = false;
  43. auto trigger = [en](bool enable = true) mutable {
  44. if (en) {
  45. cout << "fire!" << endl;
  46. }
  47. if (en or enable) {
  48. en = true;
  49. }
  50. };
  51. cout << "won't shoot" << endl;
  52. trigger(false);
  53. call_value(trigger);
  54. trigger(false);
  55. call_ref(trigger);
  56. cout << "and now ... ";
  57. trigger(false);
  58. // const ref won't work
  59. return 0;
  60. }
Success #stdin #stdout 0s 3096KB
stdin
Standard input is empty
stdout
capture by value, so we get a copy
 the lambda with a reference ...  could now be called and mutate ..  but won't, as it had to be declared mutable 
the lambda with an instance: copy
but not  the reference versions 
won't shoot
and now ... fire!