return-expr.cc 2.7 KB

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