310-Gen-VariablesInGenerators.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. // 310-Gen-VariablesInGenerator.cpp
  2. // Shows how to use variables when creating generators.
  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 -- thus they should be either captured
  6. // by value directly, or copied by the generators during construction.
  7. #include <catch2/catch_test_macros.hpp>
  8. #include <catch2/generators/catch_generators_adapters.hpp>
  9. #include <catch2/generators/catch_generators_random.hpp>
  10. TEST_CASE("Generate random doubles across different ranges",
  11. "[generator][example][advanced]") {
  12. // Workaround for old libstdc++
  13. using record = std::tuple<double, double>;
  14. // Set up 3 ranges to generate numbers from
  15. auto r = GENERATE(table<double, double>({
  16. record{3, 4},
  17. record{-4, -3},
  18. record{10, 1000}
  19. }));
  20. // This will not compile (intentionally), because it accesses a variable
  21. // auto number = GENERATE(take(50, random(std::get<0>(r), std::get<1>(r))));
  22. // GENERATE_COPY copies all variables mentioned inside the expression
  23. // thus this will work.
  24. auto number = GENERATE_COPY(take(50, random(std::get<0>(r), std::get<1>(r))));
  25. REQUIRE(std::abs(number) > 0);
  26. }
  27. // Compiling and running this file will result in 150 successful assertions