useret.cc 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // -*- mode: c++; coding: utf-8 -*-
  2. // ra-ra/examples - User defined expression templates
  3. // Daniel Llorens - 2015
  4. // Adapted from blitz++/examples/useret.cpp
  5. // Blitz++'s ETs have a static applicator, so declaring new operations requires
  6. // a new class. Thanks to C++14, declaring new ET operations is trivial in
  7. // ra:: — just declare a function.
  8. #include "ra/ra.hh"
  9. #include <iostream>
  10. using std::cout, std::endl, std::flush;
  11. double myFunction(double x)
  12. {
  13. return 1.0 / (1 + x);
  14. }
  15. double foobar(double x, double y)
  16. {
  17. return x*y;
  18. }
  19. template <class A>
  20. auto myFunction_ra(A && a)
  21. {
  22. return ra::map(myFunction, std::forward<A>(a));
  23. }
  24. template <class A, class B>
  25. auto foobar_ra(A && a, B && b)
  26. {
  27. return ra::map(foobar, std::forward<A>(a), std::forward<B>(b));
  28. }
  29. // the functions above will work with scalars as well as arrays, but you can overload the name of the scalar function by defining the overload in ra:: like so. See 'New array operations' in the manual.
  30. namespace ra {
  31. template <class A, class B>
  32. inline auto
  33. foobar(A && a, B && b)
  34. {
  35. return map(::foobar, std::forward<A>(a), std::forward<B>(b));
  36. }
  37. } // namespace ra
  38. int main()
  39. {
  40. ra::Big<double,2> A({4, 4}, 0.), B({4, 4}, 0.), C({4, 4}, 0.);
  41. A = { 0, 1, 2, 3,
  42. 4, 5, 6, 7,
  43. 8, 9, 10, 11,
  44. 12, 13, 14, 15 };
  45. C = 3;
  46. cout << "A = " << A << endl;
  47. cout << "C = " << C << endl;
  48. B = myFunction_ra(A);
  49. cout << "B = myFunction(A) = " << B << endl;
  50. B = foobar_ra(A, C);
  51. cout << "B = foobar(A, C) = " << B << endl;
  52. B = foobar(A, C);
  53. cout << "B = foobar(A, C) = " << B << endl;
  54. B = foobar_ra(A, 1.);
  55. cout << "B = foobar(A, 1.) = " << B << endl;
  56. B = foobar_ra(ra::_0, ra::_1);
  57. cout << "B = foobar(tensor::i, tensor::j) = " << B << endl;
  58. }