310-Gen-VariablesInGenerators.cpp
1 2 // Copyright Catch2 Authors 3 // Distributed under the Boost Software License, Version 1.0. 4 // (See accompanying file LICENSE.txt or copy at 5 // https://www.boost.org/LICENSE_1_0.txt) 6 7 // SPDX-License-Identifier: BSL-1.0 8 9 // 310-Gen-VariablesInGenerator.cpp 10 // Shows how to use variables when creating generators. 11 12 // Note that using variables inside generators is dangerous and should 13 // be done only if you know what you are doing, because the generators 14 // _WILL_ outlive the variables -- thus they should be either captured 15 // by value directly, or copied by the generators during construction. 16 17 #include <catch2/catch_test_macros.hpp> 18 #include <catch2/generators/catch_generators_adapters.hpp> 19 #include <catch2/generators/catch_generators_random.hpp> 20 21 TEST_CASE("Generate random doubles across different ranges", 22 "[generator][example][advanced]") { 23 // Workaround for old libstdc++ 24 using record = std::tuple<double, double>; 25 // Set up 3 ranges to generate numbers from 26 auto r = GENERATE(table<double, double>({ 27 record{3, 4}, 28 record{-4, -3}, 29 record{10, 1000} 30 })); 31 32 // This will not compile (intentionally), because it accesses a variable 33 // auto number = GENERATE(take(50, random(std::get<0>(r), std::get<1>(r)))); 34 35 // GENERATE_COPY copies all variables mentioned inside the expression 36 // thus this will work. 37 auto number = GENERATE_COPY(take(50, random(std::get<0>(r), std::get<1>(r)))); 38 39 REQUIRE(std::abs(number) > 0); 40 } 41 42 // Compiling and running this file will result in 150 successful assertions 43