libstdc++: Disable std::formatter specializations (LWG 3944)

This was just approved in Tokyo as a DR for C++23. It doesn't affect us
yet, because we don't implement the __cpp_lib_format_ranges features. We
can add the disabled specializations and add a testcase now though.

libstdc++-v3/ChangeLog:

	* include/std/format (formatter): Disable specializations that
	would allow sequences of narrow characters to be formatted as
	wchar_t without conversion, as per LWG 3944.
	* testsuite/std/format/formatter/lwg3944.cc: New test.
This commit is contained in:
Jonathan Wakely 2024-03-21 11:15:06 +00:00
parent 3763fb8970
commit 543585046d
2 changed files with 54 additions and 0 deletions

View file

@ -2478,6 +2478,29 @@ namespace __format
};
/// @}
#if defined _GLIBCXX_USE_WCHAR_T && __cpp_lib_format_ranges
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// 3944. Formatters converting sequences of char to sequences of wchar_t
namespace __format { struct __disabled; }
// std::formatter<__disabled, C> uses the primary template, which is disabled.
template<>
struct formatter<char*, wchar_t>
: private formatter<__format::__disabled, wchar_t> { };
template<>
struct formatter<const char*, wchar_t>
: private formatter<__format::__disabled, wchar_t> { };
template<size_t _Nm>
struct formatter<char[_Nm], wchar_t>
: private formatter<__format::__disabled, wchar_t> { };
template<class _Traits, class _Allocator>
struct formatter<basic_string<char, _Traits, _Allocator>, wchar_t>
: private formatter<__format::__disabled, wchar_t> { };
template<class _Traits>
struct formatter<basic_string_view<char, _Traits>, wchar_t>
: private formatter<__format::__disabled, wchar_t> { };
#endif
/// @cond undocumented
namespace __format

View file

@ -0,0 +1,31 @@
// { dg-do compile { target c++20 } }
// { dg-options "-Wno-unused-result" }
// LWG 3944. Formatters converting sequences of char to sequences of wchar_t
#include <format>
void test_lwg3944()
{
// Ill-formed in C++20 and C++23
const char* cstr = "hello";
char* str = const_cast<char*>(cstr);
std::format(L"{}", str); // { dg-error "here" }
std::format(L"{}",cstr); // { dg-error "here" }
// Ill-formed in C++20
// In C++23 they give L"['h', 'e', 'l', 'l', 'o']"
std::format(L"{}", "hello"); // { dg-error "here" }
std::format(L"{}", std::string_view("hello")); // { dg-error "here" }
std::format(L"{}", std::string("hello")); // { dg-error "here" }
#ifdef __cpp_lib_format_ranges
// LWG 3944 does not change this, it's still valid.
std::format(L"{}", std::vector{'h', 'e', 'l', 'l', 'o'});
#endif
}
// { dg-error "std::formatter must be specialized" "" { target *-*-* } 0 }
// { dg-prune-output "use of deleted function" }
// { dg-prune-output "no matching function" }
// { dg-prune-output "has no member named 'parse'" }
// { dg-prune-output "not a constant expression" }