add_typed.cpp 1.2 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/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/detail/lightweight_test.hpp>
  12. #include <vector>
  13. #include <algorithm>
  14. //[add_typed
  15. struct adder {
  16. adder(void) : sum_(0) {}
  17. int sum(const std::vector<int>& nums, const int& factor = 10) {
  18. // Explicitly specify bound variable and return types (no type-of).
  19. BOOST_LOCAL_FUNCTION(const bind(const int&) factor,
  20. bind(adder*) this_, int num, return int) {
  21. return this_->sum_ += factor * num;
  22. } BOOST_LOCAL_FUNCTION_NAME(add)
  23. std::for_each(nums.begin(), nums.end(), add);
  24. return sum_;
  25. }
  26. private:
  27. int sum_;
  28. };
  29. //]
  30. int main(void) {
  31. std::vector<int> v(3);
  32. v[0] = 1; v[1] = 2; v[2] = 3;
  33. BOOST_TEST(adder().sum(v) == 60);
  34. return boost::report_errors();
  35. }
  36. #endif // VARIADIC_MACROS