Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/catch2/catch_tostring.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@
#include <string_view>
#endif

#ifdef CATCH_CONFIG_CPP17_OPTIONAL
#include <optional>
#endif

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
Expand Down Expand Up @@ -481,6 +485,16 @@ namespace Catch {

template <typename T>
struct is_range_impl<T, void_t<decltype(begin(std::declval<T>()))>> : std::true_type {};

// Used to exclude std::optional from the generic range StringMaker so it
// does not collide with the dedicated optional StringMaker (or a
// user-provided one). std::optional models std::ranges::range since
// C++26 (P3168), so is_range<std::optional<T>> is true and both partial
// specializations would otherwise match StringMaker<std::optional<T>>.
template <typename T> struct is_optional : std::false_type {};
#if defined(CATCH_CONFIG_CPP17_OPTIONAL)
template <typename T> struct is_optional<std::optional<T>> : std::true_type {};
#endif
} // namespace Detail

template <typename T>
Expand Down Expand Up @@ -516,7 +530,9 @@ namespace Catch {
}

template<typename R>
struct StringMaker<R, std::enable_if_t<is_range<R>::value && !::Catch::Detail::IsStreamInsertable_v<R>>> {
struct StringMaker<R, std::enable_if_t<is_range<R>::value
&& !::Catch::Detail::IsStreamInsertable_v<R>
&& !::Catch::Detail::is_optional<R>::value>> {
static std::string convert( R const& range ) {
return rangeToString( range );
}
Expand Down
15 changes: 15 additions & 0 deletions tests/SelfTest/UsageTests/ToStringOptional.tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,19 @@ TEST_CASE( "std::nullopt -> toString", "[toString][optional][approvals]" ) {
REQUIRE( "{ }" == ::Catch::Detail::stringify( std::nullopt ) );
}

namespace {
struct NonStreamable { int v; };
}

// Regression: under C++26, std::optional models std::ranges::range (P3168), so
// without the is_optional carve-out in the range StringMaker the dedicated
// optional StringMaker collides with the range one and instantiation becomes
// ambiguous. This test just needs to compile.
TEST_CASE( "std::optional<NonStreamable> -> toString does not collide with range StringMaker",
"[toString][optional][approvals]" ) {
using type = std::optional<NonStreamable>;
REQUIRE( "{ }" == ::Catch::Detail::stringify( type{} ) );
REQUIRE( "{?}" == ::Catch::Detail::stringify( type{ NonStreamable{ 42 } } ) );
}

#endif // CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL