return_this.cpp 1.3 KB

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