test-return-expr.C 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // (c) Daniel Llorens - 2014
  2. // This library is free software; you can redistribute it and/or modify it under
  3. // the terms of the GNU Lesser General Public License as published by the Free
  4. // Software Foundation; either version 3 of the License, or (at your option) any
  5. // later version.
  6. /// @file test-return-expr.C
  7. /// @brief Show how careful you have to be when you return an expr object from a function.
  8. // For a real life example, see fun::project_on_plane or ra::normv. (TODO Those need tests).
  9. #include <iostream>
  10. #include "ra/complex.H"
  11. #include "ra/test.H"
  12. #include "ra/big.H"
  13. #include "ra/operators.H"
  14. #include "ra/io.H"
  15. #include <sstream>
  16. using std::cout; using std::endl; using std::flush;
  17. using real = double;
  18. template <class A>
  19. inline auto retex_vs(A const & a, real const c)
  20. {
  21. return a-std::move(c); // @NOTE without move(), ra::scalar -> ra::Scalar<real const &>, which is dangling on return.
  22. }
  23. template <class A>
  24. inline auto retex_vsref(A const & a, real const & c)
  25. {
  26. return a-c;
  27. }
  28. int main()
  29. {
  30. TestRecorder tr;
  31. auto test = [&tr](auto t, real const x)
  32. {
  33. using V = decltype(t);
  34. {
  35. V a = {1, 0, 0};
  36. std::ostringstream o;
  37. o << retex_vs(a, x);
  38. cout << "q1. " << o.str() << endl;
  39. V p;
  40. std::istringstream i(o.str());
  41. i >> p;
  42. cout << "q2. " << p << endl;
  43. tr.test_eq(1-x, p[0]);
  44. tr.test_eq(-x, p[1]);
  45. tr.test_eq(-x, p[2]);
  46. V q = retex_vs(a, 2);
  47. cout << "q3. " << q << endl;
  48. tr.test_eq(1-x, p[0]);
  49. tr.test_eq(-x, p[1]);
  50. tr.test_eq(-x, p[2]);
  51. }
  52. using V = decltype(t);
  53. {
  54. V a = {1, 0, 0};
  55. std::ostringstream o;
  56. o << retex_vsref(a, x);
  57. cout << "q1. " << o.str() << endl;
  58. V p;
  59. std::istringstream i(o.str());
  60. i >> p;
  61. cout << "q2. " << p << endl;
  62. tr.test_eq(1-x, p[0]);
  63. tr.test_eq(-x, p[1]);
  64. tr.test_eq(-x, p[2]);
  65. V q = retex_vsref(a, 2);
  66. cout << "q3. " << q << endl;
  67. tr.test_eq(1-x, p[0]);
  68. tr.test_eq(-x, p[1]);
  69. tr.test_eq(-x, p[2]);
  70. }
  71. };
  72. tr.section("vs, small");
  73. {
  74. test(ra::Small<real, 3>(), 2);
  75. test(ra::Small<real, 3>(), 3);
  76. test(ra::Small<real, 3>(), 4);
  77. }
  78. tr.section("vs, large");
  79. {
  80. test(ra::Big<real, 1>(), 2);
  81. test(ra::Big<real, 1>(), 3);
  82. test(ra::Big<real, 1>(), 4);
  83. }
  84. return tr.summary();
  85. }