311-Gen-CustomCapture.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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_test_macros.hpp>
  11. #include <catch2/generators/catch_generators_adapters.hpp>
  12. #include <catch2/generators/catch_generators_random.hpp>
  13. TEST_CASE("Generate random doubles across different ranges",
  14. "[generator][example][advanced]") {
  15. // Workaround for old libstdc++
  16. using record = std::tuple<double, double>;
  17. // Set up 3 ranges to generate numbers from
  18. auto r1 = GENERATE(table<double, double>({
  19. record{3, 4},
  20. record{-4, -3},
  21. record{10, 1000}
  22. }));
  23. auto r2(r1);
  24. // This will take r1 by reference and r2 by value.
  25. // Note that there are no advantages for doing so in this example,
  26. // it is done only for expository purposes.
  27. auto number = Catch::Generators::generate( "custom capture generator", CATCH_INTERNAL_LINEINFO,
  28. [&r1, r2]{
  29. using namespace Catch::Generators;
  30. return makeGenerators(take(50, random(std::get<0>(r1), std::get<1>(r2))));
  31. }
  32. );
  33. REQUIRE(std::abs(number) > 0);
  34. }
  35. // Compiling and running this file will result in 150 successful assertions