n2529_this.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 v;
  13. BOOST_TYPEOF_REGISTER_TYPE(v) // Register before `bind this_` below.
  14. struct v {
  15. std::vector<int> nums;
  16. v(const std::vector<int>& numbers): nums(numbers) {}
  17. void change_sign_all(const std::vector<int>& indices) {
  18. void BOOST_LOCAL_FUNCTION(bind this_, int i) { // Bind object `this`.
  19. this_->nums.at(i) = -this_->nums.at(i);
  20. } BOOST_LOCAL_FUNCTION_NAME(complement)
  21. std::for_each(indices.begin(), indices.end(), complement);
  22. }
  23. };
  24. int main(void) {
  25. std::vector<int> n(3);
  26. n[0] = 1; n[1] = 2; n[2] = 3;
  27. std::vector<int> i(2);
  28. i[0] = 0; i[1] = 2; // Will change n[0] and n[2] but not n[1].
  29. v vn(n);
  30. vn.change_sign_all(i);
  31. BOOST_TEST(vn.nums.at(0) == -1);
  32. BOOST_TEST(vn.nums.at(1) == 2);
  33. BOOST_TEST(vn.nums.at(2) == -3);
  34. return boost::report_errors();
  35. }