Debian Codegraph @

gcc/testsuite/g++.dg/cpp2a/consteval-prop2.C

raw
1 // P2564R3
2 // { dg-do compile { target c++20 } }
3 // Testcase from P2564R3.
4
5 consteval int id(int i) { return i; }
6 constexpr char id(char c) { return c; }
7
8 template<class T>
9 constexpr int f(T t) {
10 return t + id(t); // { dg-message "immediate-escalating expression .id\\(t\\)." }
11 }
12
13 auto a = &f<char>; // OK, f<char> is not an immediate function
14 auto b = &f<int>; // { dg-error "taking address of an immediate function" }
15
16 static_assert(f(3) == 6); // OK
17
18 template<class T>
19 constexpr int g(T t) { // g<int> is not an immediate function
20 return t + id(42); // because id(42) is already a constant
21 }
22
23 template<class T, class F>
24 constexpr bool is_not(T t, F f) {
25 return not f(t);
26 }
27
28 consteval bool is_even(int i) { return i % 2 == 0; }
29
30 static_assert(is_not(5, is_even)); // OK
31
32 int x = 0;
33
34 template<class T>
35 constexpr T h(T t = id(x)) { // h<int> is not an immediate function
36 return t;
37 }
38
39 template<class T>
40 constexpr T hh() { // hh<int> is an immediate function
41 return h<T>(); // { dg-error "the value of .x. is not usable in a constant expression" }
42 // { dg-message "immediate-escalating expression .id\\(x\\)." "" { target *-*-* } .-1 }
43 }
44
45 int i = hh<int>(); // { dg-error "call to consteval function|called in a constant expression" }
46 // error: hh<int>() is an immediate-escalating expression
47 // outside of an immediate-escalating function
48 struct A {
49 int x;
50 int y = id(x);
51 };
52
53 // [expr.const]#example-9 says:
54 // k<int> is not an immediate function because A(42) is a
55 // constant expression and thus not immediate-escalating
56 // In the evaluation of A(42), the member x has just been initialized
57 // to constant 42. And A(42) is constant-evaluated because "An aggregate
58 // initialization is an immediate invocation if it evaluates a default
59 // member initializer that has a subexpression that is an
60 // immediate-escalating expression."
61 template<class T>
62 constexpr int k(int) {
63 return A(42).y;
64 }
65
66 int
67 test (int i)
68 {
69 int r = g (42) + g(i);
70 int t = k<int>(42)
71 + k<int>(i); // { dg-bogus "call to|constant" "" { xfail *-*-* } }
72 return r + t;
73 }
74
75 // Just like above, but make the call to id(x) actually a constant.
76 struct A2 {
77 static constexpr int x = 42;
78 int y = id(x);
79 };
80
81 template<class T>
82 constexpr int k2(int) {
83 return A2(42).y;
84 }
85
86 int
87 test2 (int i)
88 {
89 return k2<int>(42) + k2<int>(i);
90 }