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 | |
11 | // <bit> |
12 | // |
13 | // template<class To, class From> |
14 | // constexpr To bit_cast(const From& from) noexcept; // C++20 |
15 | |
16 | // This test makes sure that std::bit_cast fails when any of the following |
17 | // constraints are violated: |
18 | // |
19 | // (1.1) sizeof(To) == sizeof(From) is true; |
20 | // (1.2) is_trivially_copyable_v<To> is true; |
21 | // (1.3) is_trivially_copyable_v<From> is true. |
22 | // |
23 | // Also check that it's ill-formed when the return type would be |
24 | // ill-formed, even though that is not explicitly mentioned in the |
25 | // specification (but it can be inferred from the synopsis). |
26 | |
27 | #include <bit> |
28 | #include <concepts> |
29 | |
30 | template<class To, class From> |
31 | concept bit_cast_is_valid = requires(From from) { |
32 | { std::bit_cast<To>(from) } -> std::same_as<To>; |
33 | }; |
34 | |
35 | // Types are not the same size |
36 | namespace ns1 { |
37 | struct To { char a; }; |
38 | struct From { char a; char b; }; |
39 | static_assert(!bit_cast_is_valid<To, From>); |
40 | static_assert(!bit_cast_is_valid<From&, From>); |
41 | } |
42 | |
43 | // To is not trivially copyable |
44 | namespace ns2 { |
45 | struct To { char a; To(To const&); }; |
46 | struct From { char a; }; |
47 | static_assert(!bit_cast_is_valid<To, From>); |
48 | } |
49 | |
50 | // From is not trivially copyable |
51 | namespace ns3 { |
52 | struct To { char a; }; |
53 | struct From { char a; From(From const&); }; |
54 | static_assert(!bit_cast_is_valid<To, From>); |
55 | } |
56 | |
57 | // The return type is ill-formed |
58 | namespace ns4 { |
59 | struct From { char a; char b; }; |
60 | static_assert(!bit_cast_is_valid<char[2], From>); |
61 | static_assert(!bit_cast_is_valid<int(), From>); |
62 | } |
63 | |