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/config.hpp> 9 #ifdef BOOST_NO_CXX11_VARIADIC_MACROS 10 # error "variadic macros required" 11 #else 12 13 #include <boost/local_function.hpp> 14 #include <boost/function.hpp> 15 #include <boost/typeof/typeof.hpp> 16 #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() 17 #include <boost/detail/lightweight_test.hpp> 18 19 struct number; 20 BOOST_TYPEOF_REGISTER_TYPE(number) // Register before `bind this_` below. 21 22 struct number { numbernumber23 number(int value) : value_(value) {} 24 incnumber25 boost::function<int (void)> inc(void) { 26 int BOOST_LOCAL_FUNCTION(bind this_) { 27 return ++this_->value_; 28 } BOOST_LOCAL_FUNCTION_NAME(i) 29 return i; 30 } 31 32 private: 33 int value_; 34 }; 35 main(void)36int main(void) { 37 number n1 = 0; // Object valid in scope where closure is used. 38 boost::function<int (void)> inc1 = n1.inc(); 39 number n2 = 0; 40 boost::function<int (void)> inc2 = n2.inc(); 41 42 BOOST_TEST(inc1() == 1); 43 BOOST_TEST(inc1() == 2); 44 BOOST_TEST(inc2() == 1); 45 BOOST_TEST(inc1() == 3); 46 return boost::report_errors(); 47 } 48 49 #endif // VARIADIC_MACROS 50 51