Files
Catch2/tests/SelfTest/UsageTests/MatchersConstexpr.tests.cpp
Martin Hořeňovský 9f0120a5e9 Support for constexpr matchers in C++20 (P0784)
To make this all work, I had to remove the stringification cache
from matchers. In theory, this can cause performance penalty in
cases where single matcher instance is stringified multiple times,
but in practice this does not happen much, and the difference is
surprisingly small anyway, because the performance of stringification
is already horrible and full of allocating strings just to throw
them away.

The matcher combinators need P2738 from C++26 to be `constexpr`.

TODO: close related issues
2026-05-11 21:19:31 +02:00

53 lines
1.6 KiB
C++

// 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
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_templated.hpp>
#if defined( CATCH_INTERNAL_CONSTEXPR_MATCHERS_ENABLED )
namespace {
struct MatchAllMatcher final : public Catch::Matchers::MatcherGenericBase {
public:
template <typename Any>
constexpr bool match( Any&& ) const {
return true;
}
std::string describe() const override {
using namespace std::string_literals;
return "Matches anything"s;
}
};
constexpr MatchAllMatcher MatchAll() { return MatchAllMatcher(); }
} // namespace
TEST_CASE( "Constexpr support for matchers", "[constexpr][matchers][approvals]" ) {
STATIC_REQUIRE( MatchAll().match( 1 ) );
STATIC_REQUIRE_THAT( 1, MatchAll() );
}
// Combining matchers needs C++26 and P2738, so they are in separate preprocessor block
# if __cpp_constexpr >= 202306L
TEST_CASE("Constexpr support for combining matchers",
"[constexpr][matchers][approvals]") {
STATIC_REQUIRE( ( MatchAll() && MatchAll() ).match( 1 ) );
STATIC_REQUIRE( ( MatchAll() || MatchAll() ).match( 1 ) );
STATIC_REQUIRE( ( !!MatchAll() ).match( 1 ) );
STATIC_REQUIRE_THAT( 1, MatchAll() && MatchAll() );
STATIC_REQUIRE_THAT( 1, MatchAll() || MatchAll() );
STATIC_REQUIRE_THAT( 1, !!MatchAll() );
}
#endif // __cpp_constexpr >= 202306L
#endif