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