Clang Project

clang_source_code/test/SemaCXX/decomposed-condition.cpp
1// RUN: %clang_cc1 -std=c++1z -Wno-binding-in-condition -verify %s
2
3struct X {
4  bool flag;
5  int data;
6  constexpr explicit operator bool() const {
7    return flag;
8  }
9  constexpr operator int() const {
10    return data;
11  }
12};
13
14namespace CondInIf {
15constexpr int f(X x) {
16  if (auto [ok, d] = x)
17    return d + int(ok);
18  else
19    return d * int(ok);
20  ok = {}; // expected-error {{use of undeclared identifier 'ok'}}
21  d = {};  // expected-error {{use of undeclared identifier 'd'}}
22}
23
24static_assert(f({true, 2}) == 3);
25static_assert(f({false, 2}) == 0);
26
27constexpr char g(char const (&x)[2]) {
28  if (auto &[a, b] = x)
29    return a;
30  else
31    return b;
32
33  if (auto [a, b] = x) // expected-error {{an array type is not allowed here}}
34    ;
35}
36
37static_assert(g("x") == 'x');
38} // namespace CondInIf
39
40namespace CondInSwitch {
41constexpr int f(int n) {
42  switch (X s = {true, n}; auto [ok, d] = s) {
43    s = {};
44  case 0:
45    return int(ok);
46  case 1:
47    return d * 10;
48  case 2:
49    return d * 40;
50  default:
51    return 0;
52  }
53  ok = {}; // expected-error {{use of undeclared identifier 'ok'}}
54  d = {};  // expected-error {{use of undeclared identifier 'd'}}
55  s = {};  // expected-error {{use of undeclared identifier 's'}}
56}
57
58static_assert(f(0) == 1);
59static_assert(f(1) == 10);
60static_assert(f(2) == 80);
61} // namespace CondInSwitch
62
63namespace CondInWhile {
64constexpr int f(int n) {
65  int m = 1;
66  while (auto [ok, d] = X{n > 1, n}) {
67    m *= d;
68    --n;
69  }
70  return m;
71  return ok; // expected-error {{use of undeclared identifier 'ok'}}
72}
73
74static_assert(f(0) == 1);
75static_assert(f(1) == 1);
76static_assert(f(4) == 24);
77} // namespace CondInWhile
78
79namespace CondInFor {
80constexpr int f(int n) {
81  int a = 1, b = 1;
82  for (X x = {true, n}; auto &[ok, d] = x; --d) {
83    if (d < 2)
84      ok = false;
85    else {
86      int x = b;
87      b += a;
88      a = x;
89    }
90  }
91  return b;
92  return d; // expected-error {{use of undeclared identifier 'd'}}
93}
94
95static_assert(f(0) == 1);
96static_assert(f(1) == 1);
97static_assert(f(2) == 2);
98static_assert(f(5) == 8);
99} // namespace CondInFor
100