Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add helper macro to declare enums with to_string.
[simgrid.git] / include / xbt / utility.hpp
1 /* Copyright (c) 2016-2021. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #ifndef XBT_UTILITY_HPP
8 #define XBT_UTILITY_HPP
9
10 #include <functional>
11 #include <tuple>
12 #include <xbt/base.h>
13
14 /** @brief Helper macro to declare enum class
15  *
16  * Declares an enum class EnumType, and a function "const char* to_c_str(EnumType)" to retrieve a C-string description
17  * for each value.
18  */
19 #define XBT_DECLARE_ENUM_CLASS(EnumType, ...)                                                                          \
20   enum class EnumType;                                                                                                 \
21   static constexpr char const* to_c_str(EnumType value)                                                                \
22   {                                                                                                                    \
23     constexpr std::array<const char*, _XBT_COUNT_ARGS(__VA_ARGS__)> names{{_XBT_STRINGIFY_ARGS(__VA_ARGS__)}};         \
24     return names[static_cast<int>(value)];                                                                             \
25   }                                                                                                                    \
26   enum class EnumType { __VA_ARGS__ } /* defined here to handle trailing semicolon */
27
28 namespace simgrid {
29 namespace xbt {
30
31 /** @brief A hash which works with more stuff
32  *
33  *  It can hash pairs: the standard hash currently doesn't include this.
34  */
35 template <class X> class hash : public std::hash<X> {
36 };
37
38 template <class X, class Y> class hash<std::pair<X, Y>> {
39 public:
40   std::size_t operator()(std::pair<X, Y> const& x) const
41   {
42     hash<X> h1;
43     hash<X> h2;
44     return h1(x.first) ^ h2(x.second);
45   }
46 };
47
48 /** @brief Comparator class for using with std::priority_queue or boost::heap.
49  *
50  * Compare two std::pair by their first element (of type double), and return true when the first is greater than the
51  * second.  Useful to have priority queues with the smallest element on top.
52  */
53 template <class Pair> class HeapComparator {
54 public:
55   bool operator()(const Pair& a, const Pair& b) const { return a.first > b.first; }
56 };
57
58 /** @brief Erase an element given by reference from a boost::intrusive::list.
59  */
60 template <class List, class Elem> inline void intrusive_erase(List& list, Elem& elem)
61 {
62   list.erase(list.iterator_to(elem));
63 }
64
65 }
66 }
67 #endif