| The Gaudi Framework v28r2p1 (f1a77ff4)

- Main Page
- Related Pages
- Modules
- Namespaces
- Classes
- Files

- File List
- File Members

reverse.h
Go to the documentation of this file.
1 #ifndef GAUDIKERNEL_REVERSE_H
2 #define GAUDIKERNEL_REVERSE_H
3 //
4 // provide a generic 'reverse' function for use in range-based for loops.
5 //
6 // example:
7 //
8 // #include "GaudiKernel/reverse.h"
9 // auto l = { 1,2,3,4 };
10 // for ( const auto& i : reverse( l ) ) std::cout << i << std::endl;
11 //
12 // Note that it is perfectly fine to reverse a temporary. The temporary
13 // will be moved into the reverse_wrapper, and thus kept alive for the
14 // duration of the loop. In case reverse is called on an lvalue, the wrapper
15 // will take a reference, so no copy will be performed. (if you wonder how
16 // the code below (very implicitly) distinguishes between the two cases,
17 // google for 'C++11 reference collapsing' -- short version: C++ does not
18 // allow references to references, so in cases where this would happen,
19 // one gets an lvalue reference)
20 //
21 // Also note that reverse_wrapper does not have a constructor, but this
22 // implies that it does meet the requirements for aggregate initializaton,
23 // which allows for {} initialization of its member.
24 //
25 #include <utility>
26
27 #include <utility>
28
29 template <typename Iterable>
30 struct reverse_wrapper { Iterable iterable; };
31
32 template <typename T>
33 reverse_wrapper<T> reverse(T&& iterable) { return { std::forward<T>(iterable) }; }
34
35
36 #if defined __GNUC__ && __GNUC__ < 5
37
38 // std::rbegin and std::rend require gcc 5.0 or later (or clang 3.5 or later)
39 template <typename T>
40 auto begin(reverse_wrapper<T>& w) -> decltype(w.iterable.rbegin()) { return w.iterable.rbegin(); }
41 template <typename T>
42 auto end(reverse_wrapper<T>& w) -> decltype(w.iterable.rend()) { return w.iterable.rend(); }
43
44 #else
45
46 #include <iterator>
47 template <typename T>
48 auto begin(reverse_wrapper<T>& w) { using std::rbegin; return rbegin(w.iterable); }
49 template <typename T>
50 auto end(reverse_wrapper<T>& w) { using std::rend; return rend(w.iterable); }
51
52 #endif
53
54
55 #endif
reverse_wrapper::iterable
Iterable iterable
Definition: reverse.h:30
begin
auto begin(reverse_wrapper< T > &w)
Definition: reverse.h:48
end
auto end(reverse_wrapper< T > &w)
Definition: reverse.h:50
reverse_wrapper
Definition: reverse.h:30
reverse
reverse_wrapper< T > reverse(T &&iterable)
Definition: reverse.h:33