add_template.cpp 1022 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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 <algorithm>
  13. //[add_template
  14. template<typename T>
  15. T total(const T& x, const T& y, const T& z) {
  16. T sum = T(), factor = 10;
  17. // Must use the `..._TPL` macros within templates.
  18. T BOOST_LOCAL_FUNCTION_TPL(const bind factor, bind& sum, T num) {
  19. return sum += factor * num;
  20. } BOOST_LOCAL_FUNCTION_NAME_TPL(add)
  21. add(x);
  22. T nums[2]; nums[0] = y; nums[1] = z;
  23. std::for_each(nums, nums + 2, add);
  24. return sum;
  25. }
  26. //]
  27. int main(void) {
  28. BOOST_TEST(total(1, 2, 3) == 60);
  29. return boost::report_errors();
  30. }
  31. #endif // VARIADIC_MACROS