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.hpp> 10 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 r = GENERATE(table<double, double>({ 17 record{3, 4}, 18 record{-4, -3}, 19 record{10, 1000} 20 })); 21 22 // This will not compile (intentionally), because it accesses a variable 23 // auto number = GENERATE(take(50, random(std::get<0>(r), std::get<1>(r)))); 24 25 // GENERATE_COPY copies all variables mentioned inside the expression 26 // thus this will work. 27 auto number = GENERATE_COPY(take(50, random(std::get<0>(r), std::get<1>(r)))); 28 29 REQUIRE(std::abs(number) > 0); 30 } 31 32 // Compiling and running this file will result in 150 successful assertions 33 34