world_this.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright (C) 2006-2009, 2012 Alexander Nasonov
  2. // Copyright (C) 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/scope_exit
  7. #include <boost/config.hpp>
  8. #ifdef BOOST_NO_CXX11_VARIADIC_MACROS
  9. # error "variadic macros required"
  10. #else
  11. #include <boost/scope_exit.hpp>
  12. #include <boost/typeof/typeof.hpp>
  13. #include <boost/typeof/std/vector.hpp>
  14. #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
  15. #include <boost/detail/lightweight_test.hpp>
  16. #include <boost/config.hpp>
  17. #include <vector>
  18. struct person {};
  19. BOOST_TYPEOF_REGISTER_TYPE(person)
  20. struct world {
  21. void add_person(person const& a_person);
  22. size_t population(void) const { return persons_.size(); }
  23. private:
  24. std::vector<person> persons_;
  25. };
  26. BOOST_TYPEOF_REGISTER_TYPE(world)
  27. void world::add_person(person const& a_person) {
  28. bool commit = false;
  29. persons_.push_back(a_person);
  30. //[world_this
  31. BOOST_SCOPE_EXIT(&commit, this_) { // Capture object `this_`.
  32. if(!commit) this_->persons_.pop_back();
  33. } BOOST_SCOPE_EXIT_END
  34. //]
  35. // ...
  36. commit = true;
  37. }
  38. int main(void) {
  39. world w;
  40. person p;
  41. w.add_person(p);
  42. BOOST_TEST(w.population() == 1);
  43. return boost::report_errors();
  44. }
  45. #endif // variadic macros