mem-fn.cc 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // -*- mode: c++; coding: utf-8 -*-
  2. // ra-ra/test - Using map with pointers to members. Until uniform call syntax is a thing.
  3. // (c) Daniel Llorens - 2018-2019
  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. #include <numeric>
  9. #include <iostream>
  10. #include "ra/test.hh"
  11. using std::cout, std::endl, std::flush, ra::TestRecorder;
  12. using real = double;
  13. struct example
  14. {
  15. float b;
  16. float & f() { return b; }
  17. };
  18. int main()
  19. {
  20. TestRecorder tr;
  21. tr.section("pointer to member");
  22. {
  23. ra::Big<example, 2> ex({2, 3}, ra::scalar(example {99}));
  24. map(std::mem_fn(&example::b), ex) = ra::_0-ra::_1;
  25. tr.test_eq(0, ex(0, 0).b);
  26. tr.test_eq(-1, ex(0, 1).b);
  27. tr.test_eq(-2, ex(0, 2).b);
  28. tr.test_eq(1, ex(1, 0).b);
  29. tr.test_eq(0, ex(1, 1).b);
  30. tr.test_eq(-1, ex(1, 2).b);
  31. map(std::mem_fn(&example::f), ex) = ra::_1-ra::_0;
  32. tr.test_eq(0, ex(0, 0).b);
  33. tr.test_eq(1, ex(0, 1).b);
  34. tr.test_eq(2, ex(0, 2).b);
  35. tr.test_eq(-1, ex(1, 0).b);
  36. tr.test_eq(0, ex(1, 1).b);
  37. tr.test_eq(1, ex(1, 2).b);
  38. }
  39. tr.section("naw that Expr uses std::invoke() we can use the member directly");
  40. {
  41. ra::Big<example, 2> ex({2, 3}, ra::scalar(example {99}));
  42. map(&example::b, ex) = ra::_0-ra::_1;
  43. tr.test_eq(0, ex(0, 0).b);
  44. tr.test_eq(-1, ex(0, 1).b);
  45. tr.test_eq(-2, ex(0, 2).b);
  46. tr.test_eq(1, ex(1, 0).b);
  47. tr.test_eq(0, ex(1, 1).b);
  48. tr.test_eq(-1, ex(1, 2).b);
  49. map(&example::f, ex) = ra::_1-ra::_0;
  50. tr.test_eq(0, ex(0, 0).b);
  51. tr.test_eq(1, ex(0, 1).b);
  52. tr.test_eq(2, ex(0, 2).b);
  53. tr.test_eq(-1, ex(1, 0).b);
  54. tr.test_eq(0, ex(1, 1).b);
  55. tr.test_eq(1, ex(1, 2).b);
  56. }
  57. return tr.summary();
  58. }