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/local_function.hpp> 9 #include <boost/typeof/typeof.hpp> 10 #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() 11 #include <boost/detail/lightweight_test.hpp> 12 #include <algorithm> 13 #include <vector> 14 15 struct calculator; 16 BOOST_TYPEOF_REGISTER_TYPE(calculator) // Register before `bind this_` below. 17 18 struct calculator { 19 std::vector<int> results; 20 factorialscalculator21 void factorials(const std::vector<int>& nums) { 22 int BOOST_LOCAL_FUNCTION( (bind this_) (int num) 23 (bool recursion)(default false) ) { 24 int result = 0; 25 26 if(num <= 0) result = 1; 27 else result = num * factorial(num - 1, true); 28 29 if(!recursion) this_->results.push_back(result); 30 return result; 31 } BOOST_LOCAL_FUNCTION_NAME(recursive factorial) 32 33 std::for_each(nums.begin(), nums.end(), factorial); 34 } 35 }; 36 main(void)37int main(void) { 38 std::vector<int> v(3); 39 v[0] = 1; v[1] = 3; v[2] = 4; 40 41 calculator calc; 42 calc.factorials(v); 43 BOOST_TEST(calc.results[0] == 1); 44 BOOST_TEST(calc.results[1] == 6); 45 BOOST_TEST(calc.results[2] == 24); 46 return boost::report_errors(); 47 } 48 49