[PATCH v2] libstdc++: Remove dead code in range_formatter::format [PR109162]

Tomasz Kamiński tkaminsk@redhat.com
Thu Apr 17 06:30:17 GMT 2025


Because the _M_format(__rg, __fc) were placed outside of if constexpr,
these method and it's childs where instantiated, even if _M_format<const _Range>
could be used.

To simplify the if constexpr chain, we introduce a __simply_formattable_range
(name based on simple-view) exposition only concept, that checks if range is
const and mutable formattable and uses same formatter specialization for
references in each case.

	PR libstdc++/109162

libstdc++-v3/ChangeLog:

	* include/std/format (__format::__simply_formattable_range): Define.
	(range_formatter::format): Do not instantiate _M_format for mutable
	 _Rg if const _Rg can be used.

Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
---
I was really unhappy with repeated ifs, so introduced an helper concept,
that I think is usable in general.

 libstdc++-v3/include/std/format | 19 ++++++++++++-------
 1 file changed, 12 insertions(+), 7 deletions(-)

diff --git a/libstdc++-v3/include/std/format b/libstdc++-v3/include/std/format
index 27253f50ea8..1780951b61d 100644
--- a/libstdc++-v3/include/std/format
+++ b/libstdc++-v3/include/std/format
@@ -5252,6 +5252,14 @@ namespace __format
       = ranges::input_range<const _Rg>
 	  && formattable<ranges::range_reference_t<const _Rg>, _CharT>;
 
+  // _Rg& and const _Rg& are both formttable and use same formatter
+  // specialization for their references.
+  template<typename _Rg, typename _CharT>
+    concept __simply_formattable_range
+      = __const_formattable_range<_Rg, _CharT>
+	  && same_as<remove_cvref_t<ranges::range_reference_t<_Rg>>,
+	             remove_cvref_t<ranges::range_reference_t<const _Rg>>>;
+
   template<typename _Rg, typename _CharT>
     using __maybe_const_range
       = __conditional_t<__const_formattable_range<_Rg, _CharT>, const _Rg, _Rg>;
@@ -5635,13 +5643,10 @@ namespace __format
 	format(_Rg&& __rg, basic_format_context<_Out, _CharT>& __fc) const
 	{
 	  using _Range = remove_reference_t<_Rg>;
-	  if constexpr (__format::__const_formattable_range<_Range, _CharT>)
-	  {
-	    using _CRef = ranges::range_reference_t<const _Range>;
-	    if constexpr (same_as<remove_cvref_t<_CRef>, _Tp>)
-	      return _M_format<const _Range>(__rg, __fc);
-	  }
-	  return _M_format(__rg, __fc);
+	  if constexpr (__format::__simply_formattable_range<_Range, _CharT>)
+	    return _M_format<const _Range>(__rg, __fc);
+	  else
+	    return _M_format(__rg, __fc);
 	}
 
     private:
-- 
2.49.0



More information about the Libstdc++ mailing list