311-Gen-CustomCapture.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // 311-Gen-CustomCapture.cpp
  2. // Shows how to provide custom capture list to the generator expression
  3. // Note that using variables inside generators is dangerous and should
  4. // be done only if you know what you are doing, because the generators
  5. // _WILL_ outlive the variables. Also, even if you know what you are
  6. // doing, you should probably use GENERATE_COPY or GENERATE_REF macros
  7. // instead. However, if your use case requires having a
  8. // per-variable custom capture list, this example shows how to achieve
  9. // that.
  10. #include <catch2/catch.hpp>
  11. TEST_CASE("Generate random doubles across different ranges",
  12. "[generator][example][advanced]") {
  13. // Workaround for old libstdc++
  14. using record = std::tuple<double, double>;
  15. // Set up 3 ranges to generate numbers from
  16. auto r1 = GENERATE(table<double, double>({
  17. record{3, 4},
  18. record{-4, -3},
  19. record{10, 1000}
  20. }));
  21. auto r2(r1);
  22. // This will take r1 by reference and r2 by value.
  23. // Note that there are no advantages for doing so in this example,
  24. // it is done only for expository purposes.
  25. auto number = Catch::Generators::generate( "custom capture generator", CATCH_INTERNAL_LINEINFO,
  26. [&r1, r2]{
  27. using namespace Catch::Generators;
  28. return makeGenerators(take(50, random(std::get<0>(r1), std::get<1>(r2))));
  29. }
  30. );
  31. REQUIRE(std::abs(number) > 0);
  32. }
  33. // Compiling and running this file will result in 150 successful assertions