add_global_functor.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Copyright (C) 2009-2012 Lorenzo Caminiti
  2. // Distributed under the Boost Software License, Version 1.0
  3. // (see accompanying file LICENSE_1_0.txt or a copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. // Home at http://www.boost.org/libs/local_function
  6. #include <boost/detail/lightweight_test.hpp>
  7. #include <algorithm>
  8. //[add_global_functor
  9. // Unfortunately, cannot be defined locally (so not a real alternative).
  10. struct global_add { // Unfortunately, boilerplate code to program the class.
  11. global_add(int& _sum, int _factor): sum(_sum), factor(_factor) {}
  12. inline void operator()(int num) { // Body uses C++ statement syntax.
  13. sum += factor * num;
  14. }
  15. private: // Unfortunately, cannot bind so repeat variable types.
  16. int& sum; // Access `sum` by reference.
  17. const int factor; // Make `factor` constant.
  18. };
  19. int main(void) {
  20. int sum = 0, factor = 10;
  21. global_add add(sum, factor);
  22. add(1);
  23. int nums[] = {2, 3};
  24. std::for_each(nums, nums + 2, add); // Passed as template parameter.
  25. BOOST_TEST(sum == 60);
  26. return boost::report_errors();
  27. }
  28. //]