Debian Codegraph @

gcc/testsuite/g++.dg/cpp23/consteval-if3.C

raw
1 // P1938R3
2 // { dg-do run { target c++20 } }
3 // { dg-options "" }
4
5 constexpr inline bool
6 is_constant_evaluated () noexcept
7 {
8 if consteval { return true; } else { return false; } // { dg-warning "'if consteval' only available with" "" { target c++20_only } }
9 }
10
11 template<int N> struct X { int v = N; };
12 X<is_constant_evaluated ()> x; // type X<true>
13 int y = 4;
14 int a = is_constant_evaluated () ? y : 1; // initializes a to 1
15 int b = is_constant_evaluated () ? 2 : y; // initializes b to 2
16 int c = y + (is_constant_evaluated () ? 2 : y); // initializes c to 2*y
17 int d = is_constant_evaluated (); // initializes d to 1
18 int e = d + is_constant_evaluated (); // initializes e to 1 + 0
19
20 struct false_type { static constexpr bool value = false; };
21 struct true_type { static constexpr bool value = true; };
22 template<class T, class U>
23 struct is_same : false_type {};
24 template<class T>
25 struct is_same<T, T> : true_type {};
26
27 constexpr int
28 foo (int x)
29 {
30 const int n = is_constant_evaluated () ? 13 : 17; // n == 13
31 int m = is_constant_evaluated () ? 13 : 17; // m might be 13 or 17 (see below)
32 char arr[n] = {}; // char[13]
33 return m + sizeof (arr) + x;
34 }
35
36 constexpr int
37 bar ()
38 {
39 const int n = is_constant_evaluated() ? 13 : 17;
40 X<n> x1;
41 X<is_constant_evaluated() ? 13 : 17> x2;
42 static_assert (is_same<decltype (x1), decltype (x2)>::value, "x1/x2's type");
43 return x1.v + x2.v;
44 }
45
46 int p = foo (0); // m == 13; initialized to 26
47 int q = p + foo (0); // m == 17 for this call; initialized to 56
48 static_assert (bar () == 26, "bar");
49
50 struct S { int a, b; };
51
52 S s = { is_constant_evaluated () ? 2 : 3, y };
53 S t = { is_constant_evaluated () ? 2 : 3, 4 };
54
55 static_assert (is_same<decltype (x), X<true> >::value, "x's type");
56
57 int
58 main ()
59 {
60 if (a != 1 || b != 2 || c != 8 || d != 1 || e != 1 || p != 26 || q != 56)
61 __builtin_abort ();
62 if (s.a != 3 || s.b != 4 || t.a != 2 || t.b != 4)
63 __builtin_abort ();
64 if (foo (y) != 34)
65 __builtin_abort ();
66 #if __cplusplus >= 201703L
67 if constexpr (foo (0) != 26)
68 __builtin_abort ();
69 #endif
70 constexpr int w = foo (0);
71 if (w != 26)
72 __builtin_abort ();
73 }