]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
libstdc++: Add missing constraints to std::bit_cast [PR105027]
authorJonathan Wakely <jwakely@redhat.com>
Wed, 23 Mar 2022 09:57:20 +0000 (09:57 +0000)
committerJonathan Wakely <jwakely@redhat.com>
Wed, 23 Mar 2022 12:17:16 +0000 (12:17 +0000)
Our std::bit_cast was relying on the compiler to check for errors inside
__builtin_bit_cast, instead of checking them as constraints. That means
std::bit_cast was not SFINAE-friendly.

This fix uses a requires-clause, so for old versions of Clang without
concepts support the function will still be unconstrained. At some point
in future we can remove the #ifdef __cpp_concepts check and rely on all
compilers having full concepts support in C++20 mode.

libstdc++-v3/ChangeLog:

PR libstdc++/105027
* include/std/bit (bit_cast): Add constraints.
* testsuite/26_numerics/bit/bit.cast/105027.cc: New test.

libstdc++-v3/include/std/bit
libstdc++-v3/testsuite/26_numerics/bit/bit.cast/105027.cc [new file with mode: 0644]

index cfd98e24eb5bc8424709082ba09d8f1e8803f3a8..a40f1ce99df45e5ccbcd6d0f187fd53189b114b7 100644 (file)
@@ -73,6 +73,10 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
     [[nodiscard]]
     constexpr _To
     bit_cast(const _From& __from) noexcept
+#ifdef __cpp_concepts
+    requires (sizeof(_To) == sizeof(_From))
+      && __is_trivially_copyable(_To) && __is_trivially_copyable(_From)
+#endif
     {
       return __builtin_bit_cast(_To, __from);
     }
diff --git a/libstdc++-v3/testsuite/26_numerics/bit/bit.cast/105027.cc b/libstdc++-v3/testsuite/26_numerics/bit/bit.cast/105027.cc
new file mode 100644 (file)
index 0000000..301d94e
--- /dev/null
@@ -0,0 +1,18 @@
+// { dg-options "-std=gnu++20" }
+// { dg-do compile { target c++20 } }
+
+// PR libstdc++/105027 - Missing constraints on std::bit_cast
+
+#include <bit>
+
+template<class T, class U>
+concept BitCastable = requires(const U& u) { std::bit_cast<T>(u); };
+
+static_assert(BitCastable<int, unsigned>); // OK
+
+static_assert(!BitCastable<int, char>); // #1: different size
+
+struct A { A(A const&); int i; };
+static_assert(!BitCastable<int, A>); // #2: not trivially copyable
+
+static_assert(!BitCastable<long, int()>); // #3: sizeof(int()) is ill-formed