Implement range-based for-statements.
[official-gcc.git] / gcc / testsuite / g++.dg / cpp0x / range-for4.C
blob96c0d90f0f02b1badd5dc8681ea63f9091c46923
1 // Test for range-based for loop with templates
3 // { dg-do run }
4 // { dg-options "-std=c++0x" }
6 #include <cstdio>
8 /* Preliminary declarations */
9 namespace pre
11   struct iterator
12   {
13     int x;
14     iterator (int v) :x(v) {}
15     iterator &operator ++() { ++x; return *this; }
16     int operator *() { return x; }
17     bool operator != (const iterator &o) { return x != o.x; }
18   };
20   struct container
21   {
22     int min, max;
23     container(int a, int b) :min(a), max(b) {}
24   };
26   iterator begin(const container &c)
27   {
28     return iterator(c.min);
29   }
31   iterator end(const container &c)
32   {
33     return iterator(c.max);
34   }
36 } //namespace pre
38 using pre::container;
39 extern "C" void abort(void);
41 container run_me_just_once()
43     static bool run = false;
44     if (run)
45         abort();
46     run = true;
47     return container(1,2);
50 /* Template with dependent expression. */
51 /* Template with dependent expression. */
52 template<typename T> int test1(const T &r)
54   int t = 0;
55   for (int i : r)
56     t += i;
57   return t;
60 /* Template with non-dependent expression and dependent declaration. */
61 template<typename T> int test2(const container &r)
63   int t = 0;
64   for (T i : r)
65     t += i;
66   return t;
69 /* Template with non-dependent expression (array) and dependent declaration. */
70 template<typename T> int test2(const int (&r)[4])
72   int t = 0;
73   for (T i : r)
74     t += i;
75   return t;
78 /* Template with non-dependent expression and auto declaration. */
79 template<typename T> int test3(const container &r)
81   int t = 0;
82   for (auto i : r)
83     t += i;
84   return t;
87 /* Template with non-dependent expression (array) and auto declaration. */
88 template<typename T> int test3(const int (&r)[4])
90   int t = 0;
91   for (auto i : r)
92     t += i;
93   return t;
96 int main ()
98   container c(1,5);
99   int a[4] = {5,6,7,8};
101   for (auto x : run_me_just_once())
102       ;
104   if (test1 (c) != 10)
105     abort();
106   if (test1 (a) != 26)
107     abort();
109   if (test2<int> (c) != 10)
110     abort();
111   if (test2<int> (a) != 26)
112     abort();
114   if (test3<int> (c) != 10)
115     abort();
116   if (test3<int> (a) != 26)
117     abort();
118   return 0;