1 // Copyright 2018 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.
5 #ifndef BASE_TRAITS_BAG_H_
6 #define BASE_TRAITS_BAG_H_
8 #include <initializer_list>
10 #include <type_traits>
13 #include "base/parameter_pack.h"
14 #include "third_party/abseil-cpp/absl/types/optional.h"
16 // A bag of Traits (structs / enums / etc...) can be an elegant alternative to
17 // the builder pattern and multiple default arguments for configuring things.
18 // Traits are terser than the builder pattern and can be evaluated at compile
19 // time, however they require the use of variadic templates which complicates
20 // matters. This file contains helpers that make Traits easier to use.
22 // WARNING: Trait bags are currently too heavy for non-constexpr usage in prod
23 // code due to template bloat, although adding NOINLINE to template constructors
24 // configured via trait bags can help.
27 // struct EnableFeatureX {};
28 // struct UnusedTrait {};
29 // enum Color { RED, BLUE };
31 // struct ValidTraits {
32 // ValidTraits(EnableFeatureX);
33 // ValidTraits(Color);
36 // DoSomethingAwesome(); // Use defaults (Color::BLUE &
37 // // feature X not enabled)
38 // DoSomethingAwesome(EnableFeatureX(), // Turn feature X on
39 // Color::RED); // And make it red.
40 // DoSomethingAwesome(UnusedTrait(), // Compile time error.
43 // DoSomethingAwesome might be defined as:
45 // template <class... ArgTypes,
46 // class CheckArgumentsAreValid = std::enable_if_t<
47 // trait_helpers::AreValidTraits<ValidTraits,
48 // ArgTypes...>::value>>
49 // constexpr void DoSomethingAwesome(ArgTypes... args)
50 // : enable_feature_x(
51 // trait_helpers::HasTrait<EnableFeatureX, ArgTypes...>()),
52 // color(trait_helpers::GetEnum<Color, EnumTraitA::BLUE>(args...)) {}
55 namespace trait_helpers {
57 // Represents a trait that has been removed by a predicate.
60 // Predicate used to remove any traits from the given list of types by
61 // converting them to EmptyTrait. E.g.
63 // template <typename... Args>
64 // void MyFunc(Args... args) {
65 // DoSomethingWithTraits(
66 // base::trait_helpers::Exclude<UnwantedTrait1,
67 // UnwantedTrait2>::Filter(args)...);
70 // NB It's possible to actually remove the unwanted trait from the pack, but
71 // that requires constructing a filtered tuple and applying it to the function,
72 // which isn't worth the complexity over ignoring EmptyTrait.
73 template <typename... TraitsToExclude>
76 static constexpr auto Filter(T t) {
77 if constexpr (ParameterPack<TraitsToExclude...>::template HasType<
86 // CallFirstTag is an argument tag that helps to avoid ambiguous overloaded
87 // functions. When the following call is made:
88 // func(CallFirstTag(), arg...);
89 // the compiler will give precedence to an overload candidate that directly
90 // takes CallFirstTag. Another overload that takes CallSecondTag will be
91 // considered iff the preferred overload candidates were all invalids and
92 // therefore discarded.
93 struct CallSecondTag {};
94 struct CallFirstTag : CallSecondTag {};
96 // A trait filter class |TraitFilterType| implements the protocol to get a value
97 // of type |ArgType| from an argument list and convert it to a value of type
98 // |TraitType|. If the argument list contains an argument of type |ArgType|, the
99 // filter class will be instantiated with that argument. If the argument list
100 // contains no argument of type |ArgType|, the filter class will be instantiated
101 // using the default constructor if available; a compile error is issued
102 // otherwise. The filter class must have the conversion operator TraitType()
103 // which returns a value of type TraitType.
105 // |InvalidTrait| is used to return from GetTraitFromArg when the argument is
106 // not compatible with the desired trait.
107 struct InvalidTrait {};
109 // Returns an object of type |TraitFilterType| constructed from |arg| if
110 // compatible, or |InvalidTrait| otherwise.
111 template <class TraitFilterType,
113 class CheckArgumentIsCompatible = std::enable_if_t<
114 std::is_constructible_v<TraitFilterType, ArgType>>>
115 constexpr TraitFilterType GetTraitFromArg(CallFirstTag, ArgType arg) {
116 return TraitFilterType(arg);
119 template <class TraitFilterType, class ArgType>
120 constexpr InvalidTrait GetTraitFromArg(CallSecondTag, ArgType arg) {
121 return InvalidTrait();
124 // Returns an object of type |TraitFilterType| constructed from a compatible
125 // argument in |args...|, or default constructed if none of the arguments are
126 // compatible. This is the implementation of GetTraitFromArgList() with a
127 // disambiguation tag.
128 template <class TraitFilterType,
130 class TestCompatibleArgument = std::enable_if_t<
131 any_of({std::is_constructible_v<TraitFilterType, ArgTypes>...})>>
132 constexpr TraitFilterType GetTraitFromArgListImpl(CallFirstTag,
134 return std::get<TraitFilterType>(std::make_tuple(
135 GetTraitFromArg<TraitFilterType>(CallFirstTag(), args)...));
138 template <class TraitFilterType, class... ArgTypes>
139 constexpr TraitFilterType GetTraitFromArgListImpl(CallSecondTag,
141 static_assert(std::is_constructible_v<TraitFilterType>,
142 "The traits bag is missing a required trait.");
143 return TraitFilterType();
146 // Constructs an object of type |TraitFilterType| from a compatible argument in
147 // |args...|, or using the default constructor, and returns its associated trait
148 // value using conversion to |TraitFilterType::ValueType|. If there are more
149 // than one compatible argument in |args|, generates a compile-time error.
150 template <class TraitFilterType, class... ArgTypes>
151 constexpr typename TraitFilterType::ValueType GetTraitFromArgList(
154 count({std::is_constructible_v<TraitFilterType, ArgTypes>...}, true) <= 1,
155 "The traits bag contains multiple traits of the same type.");
156 return GetTraitFromArgListImpl<TraitFilterType>(CallFirstTag(), args...);
159 // Helper class to implemnent a |TraitFilterType|.
160 template <typename T, typename _ValueType = T>
161 struct BasicTraitFilter {
162 using ValueType = _ValueType;
164 constexpr BasicTraitFilter(ValueType v) : value(v) {}
166 constexpr operator ValueType() const { return value; }
168 ValueType value = {};
171 template <typename ArgType, ArgType DefaultValue>
172 struct EnumTraitFilter : public BasicTraitFilter<ArgType> {
173 constexpr EnumTraitFilter() : BasicTraitFilter<ArgType>(DefaultValue) {}
174 constexpr EnumTraitFilter(ArgType arg) : BasicTraitFilter<ArgType>(arg) {}
177 template <typename ArgType>
178 struct OptionalEnumTraitFilter
179 : public BasicTraitFilter<ArgType, absl::optional<ArgType>> {
180 constexpr OptionalEnumTraitFilter()
181 : BasicTraitFilter<ArgType, absl::optional<ArgType>>(absl::nullopt) {}
182 constexpr OptionalEnumTraitFilter(ArgType arg)
183 : BasicTraitFilter<ArgType, absl::optional<ArgType>>(arg) {}
186 // Tests whether multiple given argtument types are all valid traits according
187 // to the provided ValidTraits. To use, define a ValidTraits
188 template <typename ArgType>
189 struct RequiredEnumTraitFilter : public BasicTraitFilter<ArgType> {
190 constexpr RequiredEnumTraitFilter(ArgType arg)
191 : BasicTraitFilter<ArgType>(arg) {}
194 // Note EmptyTrait is always regarded as valid to support filtering.
195 template <class ValidTraits, class T>
196 using IsValidTrait = std::disjunction<std::is_constructible<ValidTraits, T>,
197 std::is_same<T, EmptyTrait>>;
199 // Tests whether a given trait type is valid or invalid by testing whether it is
200 // convertible to the provided ValidTraits type. To use, define a ValidTraits
203 // struct ValidTraits {
204 // ValidTraits(MyTrait);
208 // You can 'inherit' valid traits like so:
210 // struct MoreValidTraits {
211 // MoreValidTraits(ValidTraits); // Pull in traits from ValidTraits.
212 // MoreValidTraits(MyOtherTrait);
215 template <class ValidTraits, class... ArgTypes>
216 using AreValidTraits =
217 std::bool_constant<all_of({IsValidTrait<ValidTraits, ArgTypes>::value...})>;
219 // Helper to make getting an enum from a trait more readable.
220 template <typename Enum, typename... Args>
221 static constexpr Enum GetEnum(Args... args) {
222 return GetTraitFromArgList<RequiredEnumTraitFilter<Enum>>(args...);
225 // Helper to make getting an enum from a trait with a default more readable.
226 template <typename Enum, Enum DefaultValue, typename... Args>
227 static constexpr Enum GetEnum(Args... args) {
228 return GetTraitFromArgList<EnumTraitFilter<Enum, DefaultValue>>(args...);
231 // Helper to make getting an optional enum from a trait with a default more
233 template <typename Enum, typename... Args>
234 static constexpr absl::optional<Enum> GetOptionalEnum(Args... args) {
235 return GetTraitFromArgList<OptionalEnumTraitFilter<Enum>>(args...);
238 // Helper to make checking for the presence of a trait more readable.
239 template <typename Trait, typename... Args>
240 struct HasTrait : ParameterPack<Args...>::template HasType<Trait> {
241 static_assert(count({std::is_constructible_v<Trait, Args>...}, true) <= 1,
242 "The traits bag contains multiple traits of the same type.");
245 // If you need a template vararg constructor to delegate to a private
246 // constructor, you may need to add this to the private constructor to ensure
247 // it's not matched by accident.
248 struct NotATraitTag {};
250 } // namespace trait_helpers
253 #endif // BASE_TRAITS_BAG_H_