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