1 // Copyright 2019 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef BASE_PARAMETER_PACK_H_
6 #define BASE_PARAMETER_PACK_H_
7
8 #include <stddef.h>
9
10 #include <initializer_list>
11 #include <tuple>
12 #include <type_traits>
13
14 #include "base/containers/contains.h"
15
16 namespace base {
17
18 // Checks if any of the elements in |ilist| is true.
any_of(std::initializer_list<bool> ilist)19 inline constexpr bool any_of(std::initializer_list<bool> ilist) {
20 return base::Contains(ilist, true);
21 }
22
23 // Checks if all of the elements in |ilist| are true.
all_of(std::initializer_list<bool> ilist)24 inline constexpr bool all_of(std::initializer_list<bool> ilist) {
25 return !base::Contains(ilist, false);
26 }
27
28 // Counts the elements in |ilist| that are equal to |value|.
29 // Similar to std::count for the case of constexpr initializer_list.
30 template <class T>
count(std::initializer_list<T> ilist,T value)31 inline constexpr size_t count(std::initializer_list<T> ilist, T value) {
32 size_t c = 0;
33 for (const auto& v : ilist) {
34 c += (v == value);
35 }
36 return c;
37 }
38
39 constexpr size_t pack_npos = static_cast<size_t>(-1);
40
41 template <typename... Ts>
42 struct ParameterPack {
43 // Checks if |Type| occurs in the parameter pack.
44 template <typename Type>
45 using HasType =
46 std::bool_constant<any_of({std::is_same<Type, Ts>::value...})>;
47
48 // Checks if the parameter pack only contains |Type|.
49 template <typename Type>
50 using OnlyHasType =
51 std::bool_constant<all_of({std::is_same<Type, Ts>::value...})>;
52
53 // Checks if |Type| occurs only once in the parameter pack.
54 template <typename Type>
55 using IsUniqueInPack =
56 std::bool_constant<count({std::is_same<Type, Ts>::value...}, true) == 1>;
57
58 // Returns the zero-based index of |Type| within |Pack...| or |pack_npos| if
59 // it's not within the pack.
60 template <typename Type>
IndexInPackParameterPack61 static constexpr size_t IndexInPack() {
62 size_t index = 0;
63 for (bool value : {std::is_same<Type, Ts>::value...}) {
64 if (value)
65 return index;
66 index++;
67 }
68 return pack_npos;
69 }
70
71 // Helper for extracting the Nth type from a parameter pack.
72 template <size_t N>
73 using NthType = std::tuple_element_t<N, std::tuple<Ts...>>;
74
75 // Checks if every type in the parameter pack is the same.
76 using IsAllSameType =
77 std::bool_constant<all_of({std::is_same<NthType<0>, Ts>::value...})>;
78 };
79
80 } // namespace base
81
82 #endif // BASE_PARAMETER_PACK_H_
83