add_this.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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/typeof/typeof.hpp>
  12. #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
  13. #include <boost/detail/lightweight_test.hpp>
  14. #include <vector>
  15. #include <algorithm>
  16. struct adder;
  17. BOOST_TYPEOF_REGISTER_TYPE(adder) // Register before `bind this_` below.
  18. //[add_this
  19. struct adder {
  20. adder() : sum_(0) {}
  21. int sum(const std::vector<int>& nums, const int factor = 10) {
  22. void BOOST_LOCAL_FUNCTION(const bind factor, bind this_, int num) {
  23. this_->sum_ += factor * num; // Use `this_` instead of `this`.
  24. } BOOST_LOCAL_FUNCTION_NAME(add)
  25. std::for_each(nums.begin(), nums.end(), add);
  26. return sum_;
  27. }
  28. private:
  29. int sum_;
  30. };
  31. //]
  32. int main(void) {
  33. std::vector<int> v(3);
  34. v[0] = 1; v[1] = 2; v[2] = 3;
  35. BOOST_TEST(adder().sum(v) == 60);
  36. return boost::report_errors();
  37. }
  38. #endif // VARIADIC_MACROS