310-Gen-VariablesInGenerators.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233
  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.hpp>
  8. TEST_CASE("Generate random doubles across different ranges",
  9. "[generator][example][advanced]") {
  10. // Workaround for old libstdc++
  11. using record = std::tuple<double, double>;
  12. // Set up 3 ranges to generate numbers from
  13. auto r = GENERATE(table<double, double>({
  14. record{3, 4},
  15. record{-4, -3},
  16. record{10, 1000}
  17. }));
  18. // This will not compile (intentionally), because it accesses a variable
  19. // auto number = GENERATE(take(50, random(std::get<0>(r), std::get<1>(r))));
  20. // GENERATE_COPY copies all variables mentioned inside the expression
  21. // thus this will work.
  22. auto number = GENERATE_COPY(take(50, random(std::get<0>(r), std::get<1>(r))));
  23. REQUIRE(std::abs(number) > 0);
  24. }
  25. // Compiling and running this file will result in 150 successful assertions