return_this_seq.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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/local_function.hpp>
  7. #include <boost/function.hpp>
  8. #include <boost/typeof/typeof.hpp>
  9. #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
  10. #include <boost/detail/lightweight_test.hpp>
  11. struct number;
  12. BOOST_TYPEOF_REGISTER_TYPE(number) // Register before `bind this_` below.
  13. struct number {
  14. number(int value) : value_(value) {}
  15. boost::function<int (void)> inc(void) {
  16. int BOOST_LOCAL_FUNCTION( (bind this_) ) {
  17. return ++this_->value_;
  18. } BOOST_LOCAL_FUNCTION_NAME(i)
  19. return i;
  20. }
  21. private:
  22. int value_;
  23. };
  24. int main(void) {
  25. number n1 = 0; // Object valid in scope where closure is used.
  26. boost::function<int (void)> inc1 = n1.inc();
  27. number n2 = 0;
  28. boost::function<int (void)> inc2 = n2.inc();
  29. BOOST_TEST(inc1() == 1);
  30. BOOST_TEST(inc1() == 2);
  31. BOOST_TEST(inc2() == 1);
  32. BOOST_TEST(inc1() == 3);
  33. return boost::report_errors();
  34. }