From 863c662c0eff026300f4d729a7054e90d6d12cdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Ho=C5=99e=C5=88ovsk=C3=BD?= Date: Tue, 2 Jan 2024 23:27:13 +0100 Subject: [PATCH] Fix adding Opts with | to lvalue Parser This is the recommended way of adding new Opts in our documentation for using custom main, but we did not compile the code to see if it works. We now compile the example as part of the BUILD_EXAMPLES option. Fixes #2787 --- examples/232-Cfg-CustomMain.cpp | 41 +++++++++++++++++++++++++++++ examples/CMakeLists.txt | 1 + src/catch2/internal/catch_clara.hpp | 4 ++- 3 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 examples/232-Cfg-CustomMain.cpp diff --git a/examples/232-Cfg-CustomMain.cpp b/examples/232-Cfg-CustomMain.cpp new file mode 100644 index 00000000..69fba7f1 --- /dev/null +++ b/examples/232-Cfg-CustomMain.cpp @@ -0,0 +1,41 @@ + +// Copyright Catch2 Authors +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// SPDX-License-Identifier: BSL-1.0 + +// 232-Cfg-CustomMain.cpp +// Show how to use custom main and add a custom option to the CLI parser + +#include + +#include + +int main(int argc, char** argv) { + Catch::Session session; // There must be exactly one instance + + int height = 0; // Some user variable you want to be able to set + + // Build a new parser on top of Catch2's + using namespace Catch::Clara; + auto cli + = session.cli() // Get Catch2's command line parser + | Opt( height, "height" ) // bind variable to a new option, with a hint string + ["--height"] // the option names it will respond to + ("how high?"); // description string for the help output + + // Now pass the new composite back to Catch2 so it uses that + session.cli( cli ); + + // Let Catch2 (using Clara) parse the command line + int returnCode = session.applyCommandLine( argc, argv ); + if( returnCode != 0 ) // Indicates a command line error + return returnCode; + + // if set on the command line then 'height' is now set at this point + std::cout << "height: " << height << std::endl; + + return session.run(); +} diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 52010400..82734ada 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -30,6 +30,7 @@ set( SOURCES_IDIOMATIC_EXAMPLES 110-Fix-ClassFixture.cpp 120-Bdd-ScenarioGivenWhenThen.cpp 210-Evt-EventListeners.cpp + 232-Cfg-CustomMain.cpp 300-Gen-OwnGenerator.cpp 301-Gen-MapTypeConversion.cpp 302-Gen-Table.cpp diff --git a/src/catch2/internal/catch_clara.hpp b/src/catch2/internal/catch_clara.hpp index b7001db2..d869593b 100644 --- a/src/catch2/internal/catch_clara.hpp +++ b/src/catch2/internal/catch_clara.hpp @@ -673,7 +673,9 @@ namespace Catch { template friend Parser operator|( Parser const& p, T&& rhs ) { - return Parser( p ) |= CATCH_FORWARD(rhs); + Parser temp( p ); + temp |= rhs; + return temp; } template