| 1 | // 310-Gen-VariablesInGenerator.cpp |
| 2 | // Shows how to use variables when creating generators. |
| 3 | |
| 4 | // Note that using variables inside generators is dangerous and should |
| 5 | // be done only if you know what you are doing, because the generators |
| 6 | // _WILL_ outlive the variables -- thus they should be either captured |
| 7 | // by value directly, or copied by the generators during construction. |
| 8 | |
| 9 | #include <catch2/catch_test_macros.hpp> |
| 10 | #include <catch2/generators/catch_generators_adapters.hpp> |
| 11 | #include <catch2/generators/catch_generators_random.hpp> |
| 12 | |
| 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 r = GENERATE(table<double, double>({ |
| 19 | record{3, 4}, |
| 20 | record{-4, -3}, |
| 21 | record{10, 1000} |
| 22 | })); |
| 23 | |
| 24 | // This will not compile (intentionally), because it accesses a variable |
| 25 | // auto number = GENERATE(take(50, random(std::get<0>(r), std::get<1>(r)))); |
| 26 | |
| 27 | // GENERATE_COPY copies all variables mentioned inside the expression |
| 28 | // thus this will work. |
| 29 | auto number = GENERATE_COPY(take(50, random(std::get<0>(r), std::get<1>(r)))); |
| 30 | |
| 31 | REQUIRE(std::abs(number) > 0); |
| 32 | } |
| 33 | |
| 34 | // Compiling and running this file will result in 150 successful assertions |
| 35 |