Prevent IsOneOf unused template specialization instantiation
authorstryku <stryku2393@gmail.com>
Fri, 28 Jul 2017 20:05:08 +0000 (13:05 -0700)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Fri, 28 Jul 2017 20:05:40 +0000 (13:05 -0700)
Summary:
Current `IsOneOf` implementation does unnecessary work because it instantiates all of the possible template specializations, even if type is same as the first of the tested ones. E.g.
`IsOneOf<char, char, int, float>` will instantiate:
```
IsOneOf<char, char, int, float>
IsOneOf<char, char, int>
IsOneOf<char, char>
IsOneOf<char>
```

With the proposed inheritance, compiler will stop initializing at the first match.
Closes https://github.com/facebook/folly/pull/643

Reviewed By: ericniebler

Differential Revision: D5482783

Pulled By: yfeldblum

fbshipit-source-id: 3d04c750ce72fa9b19b4d0588cccfb396a9e0715

folly/Traits.h

index 03442bea179d8453d02fe9b8da31308576314402..eed02dc620a37e0bce2fdb123e570550196c9a56 100644 (file)
@@ -386,8 +386,14 @@ struct Bools {
 
 // Lighter-weight than Conjunction, but evaluates all sub-conditions eagerly.
 template <class... Ts>
-struct StrictConjunction
-    : std::is_same<Bools<Ts::value..., true>, Bools<true, Ts::value...>> {};
+struct StrictConjunction 
+  : std::is_same<Bools<Ts::value...>, Bools<(Ts::value || true)...>> {};
+
+template <class... Ts>
+struct StrictDisjunction 
+  : Negation<
+      std::is_same<Bools<Ts::value...>, Bools<(Ts::value && false)...>>
+    > {};
 
 } // namespace folly
 
@@ -509,15 +515,8 @@ struct IsRelocatable< std::pair<T, U> >
         IsRelocatable<U>::value> {};
 
 // Is T one of T1, T2, ..., Tn?
-template <class T, class... Ts>
-struct IsOneOf {
-  enum { value = false };
-};
-
-template <class T, class T1, class... Ts>
-struct IsOneOf<T, T1, Ts...> {
-  enum { value = std::is_same<T, T1>::value || IsOneOf<T, Ts...>::value };
-};
+template <typename T, typename... Ts>
+using IsOneOf = StrictDisjunction<std::is_same<T, Ts>...>;
 
 /*
  * Complementary type traits for integral comparisons.