1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 // UNSUPPORTED: c++03, c++11, c++14, c++17
10 // UNSUPPORTED: libcpp-no-concepts
11 
12 // <bit>
13 //
14 // template<class To, class From>
15 //   constexpr To bit_cast(const From& from) noexcept; // C++20
16 
17 // This test makes sure that std::bit_cast fails when any of the following
18 // constraints are violated:
19 //
20 //      (1.1) sizeof(To) == sizeof(From) is true;
21 //      (1.2) is_trivially_copyable_v<To> is true;
22 //      (1.3) is_trivially_copyable_v<From> is true.
23 //
24 // Also check that it's ill-formed when the return type would be
25 // ill-formed, even though that is not explicitly mentioned in the
26 // specification (but it can be inferred from the synopsis).
27 
28 #include <bit>
29 #include <concepts>
30 
31 template<class To, class From>
32 concept bit_cast_is_valid = requires(From from) {
33     { std::bit_cast<To>(from) } -> std::same_as<To>;
34 };
35 
36 // Types are not the same size
37 namespace ns1 {
38     struct To { char a; };
39     struct From { char a; char b; };
40     static_assert(!bit_cast_is_valid<To, From>);
41     static_assert(!bit_cast_is_valid<From&, From>);
42 }
43 
44 // To is not trivially copyable
45 namespace ns2 {
46     struct To { char a; To(To const&); };
47     struct From { char a; };
48     static_assert(!bit_cast_is_valid<To, From>);
49 }
50 
51 // From is not trivially copyable
52 namespace ns3 {
53     struct To { char a; };
54     struct From { char a; From(From const&); };
55     static_assert(!bit_cast_is_valid<To, From>);
56 }
57 
58 // The return type is ill-formed
59 namespace ns4 {
60     struct From { char a; char b; };
61     static_assert(!bit_cast_is_valid<char[2], From>);
62     static_assert(!bit_cast_is_valid<int(), From>);
63 }
64