2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 // @author: Andrei Alexandrescu
23 #include <type_traits>
26 #include <folly/Portability.h>
28 // libc++ doesn't provide this header, nor does msvc
29 #ifdef FOLLY_HAVE_BITS_CXXCONFIG_H
30 // This file appears in two locations: inside fbcode and in the
31 // libstdc++ source code (when embedding fbstring as std::string).
32 // To aid in this schizophrenic use, two macros are defined in
34 // _LIBSTDCXX_FBSTRING - Set inside libstdc++. This is useful to
35 // gate use inside fbcode v. libstdc++
36 #include <bits/c++config.h>
39 #define FOLLY_CREATE_HAS_MEMBER_TYPE_TRAITS(classname, type_name) \
40 template <typename TTheClass_> \
41 struct classname##__folly_traits_impl__ { \
42 template <typename UTheClass_> \
43 static std::true_type test(typename UTheClass_::type_name*); \
45 static std::false_type test(...); \
47 template <typename TTheClass_> \
48 using classname = decltype( \
49 classname##__folly_traits_impl__<TTheClass_>::template test<TTheClass_>( \
52 #define FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, cv_qual) \
53 template <typename TTheClass_, typename RTheReturn_, typename... TTheArgs_> \
54 struct classname##__folly_traits_impl__< \
56 RTheReturn_(TTheArgs_...) cv_qual> { \
58 typename UTheClass_, \
59 RTheReturn_ (UTheClass_::*)(TTheArgs_...) cv_qual> \
61 template <typename UTheClass_> \
62 static std::true_type test(sfinae<UTheClass_, &UTheClass_::func_name>*); \
64 static std::false_type test(...); \
68 * The FOLLY_CREATE_HAS_MEMBER_FN_TRAITS is used to create traits
69 * classes that check for the existence of a member function with
70 * a given name and signature. It currently does not support
71 * checking for inherited members.
73 * Such classes receive two template parameters: the class to be checked
74 * and the signature of the member function. A static boolean field
75 * named `value` (which is also constexpr) tells whether such member
78 * Each traits class created is bound only to the member name, not to
79 * its signature nor to the type of the class containing it.
81 * Say you need to know if a given class has a member function named
82 * `test` with the following signature:
86 * You'd need this macro to create a traits class to check for a member
87 * named `test`, and then use this traits class to check for the signature:
91 * FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_test_traits, test);
93 * } // unnamed-namespace
96 * cout << "Does class Foo have a member int test() const? "
97 * << boolalpha << has_test_traits<Foo, int() const>::value;
100 * You can use the same traits class to test for a completely different
101 * signature, on a completely different class, as long as the member name
105 * cout << "Does class Foo have a member int test()? "
106 * << boolalpha << has_test_traits<Foo, int()>::value;
107 * cout << "Does class Foo have a member int test() const? "
108 * << boolalpha << has_test_traits<Foo, int() const>::value;
109 * cout << "Does class Bar have a member double test(const string&, long)? "
110 * << boolalpha << has_test_traits<Bar, double(const string&, long)>::value;
113 * @author: Marcelo Juchem <marcelo@fb.com>
115 #define FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(classname, func_name) \
116 template <typename, typename> \
117 struct classname##__folly_traits_impl__; \
118 FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, ); \
119 FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, const); \
120 FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL( \
121 classname, func_name, /* nolint */ volatile); \
122 FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL( \
123 classname, func_name, /* nolint */ volatile const); \
124 template <typename TTheClass_, typename TTheSignature_> \
126 decltype(classname##__folly_traits_impl__<TTheClass_, TTheSignature_>:: \
127 template test<TTheClass_>(nullptr))
136 * using decayed = typename std::decay<T>::type;
138 * With the C++14 standard trait aliases, we could use:
140 * using decayed = std::decay_t<T>;
142 * Without them, we could use:
144 * using decayed = _t<std::decay<T>>;
146 * Also useful for any other library with template types having dependent
147 * member types named `type`, like the standard trait types.
149 template <typename T>
150 using _t = typename T::type;
153 * IsRelocatable<T>::value describes the ability of moving around
154 * memory a value of type T by using memcpy (as opposed to the
155 * conservative approach of calling the copy constructor and then
156 * destroying the old temporary. Essentially for a relocatable type,
157 * the following two sequences of code should be semantically
160 * void move1(T * from, T * to) {
165 * void move2(T * from, T * to) {
166 * memcpy(to, from, sizeof(T));
169 * Most C++ types are relocatable; the ones that aren't would include
170 * internal pointers or (very rarely) would need to update remote
171 * pointers to pointers tracking them. All C++ primitive types and
172 * type constructors are relocatable.
174 * This property can be used in a variety of optimizations. Currently
175 * fbvector uses this property intensively.
177 * The default conservatively assumes the type is not
178 * relocatable. Several specializations are defined for known
179 * types. You may want to add your own specializations. Do so in
180 * namespace folly and make sure you keep the specialization of
181 * IsRelocatable<SomeStruct> in the same header as SomeStruct.
183 * You may also declare a type to be relocatable by including
184 * `typedef std::true_type IsRelocatable;`
185 * in the class header.
187 * It may be unset in a base class by overriding the typedef to false_type.
190 * IsTriviallyCopyable describes the value semantics property. C++11 contains
191 * the type trait is_trivially_copyable; however, it is not yet implemented
192 * in gcc (as of 4.7.1), and the user may wish to specify otherwise.
195 * IsZeroInitializable describes the property that default construction is the
196 * same as memset(dst, 0, sizeof(T)).
199 namespace traits_detail {
201 #define FOLLY_HAS_TRUE_XXX(name) \
202 FOLLY_CREATE_HAS_MEMBER_TYPE_TRAITS(has_##name, name); \
204 struct name##_is_true : std::is_same<typename T::name, std::true_type> {}; \
206 struct has_true_##name : std::conditional< \
207 has_##name<T>::value, \
209 std::false_type>::type {};
211 FOLLY_HAS_TRUE_XXX(IsRelocatable)
212 FOLLY_HAS_TRUE_XXX(IsZeroInitializable)
213 FOLLY_HAS_TRUE_XXX(IsTriviallyCopyable)
215 #undef FOLLY_HAS_TRUE_XXX
217 // Older versions of libstdc++ do not provide std::is_trivially_copyable
218 #if defined(__clang__) && !defined(_LIBCPP_VERSION)
220 struct is_trivially_copyable
221 : std::integral_constant<bool, __is_trivially_copyable(T)> {};
222 #elif defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 5
224 struct is_trivially_copyable : std::is_trivial<T> {};
227 using is_trivially_copyable = std::is_trivially_copyable<T>;
233 /* implicit */ Ignore(const T&) {}
235 const Ignore& operator=(T const&) const { return *this; }
239 using Ignored = Ignore;
241 namespace traits_detail_IsEqualityComparable {
242 Ignore operator==(Ignore, Ignore);
244 template <class T, class U = T>
245 struct IsEqualityComparable
246 : std::is_convertible<
247 decltype(std::declval<T>() == std::declval<U>()),
252 /* using override */ using traits_detail_IsEqualityComparable::
253 IsEqualityComparable;
255 namespace traits_detail_IsLessThanComparable {
256 Ignore operator<(Ignore, Ignore);
258 template <class T, class U = T>
259 struct IsLessThanComparable
260 : std::is_convertible<
261 decltype(std::declval<T>() < std::declval<U>()),
266 /* using override */ using traits_detail_IsLessThanComparable::
267 IsLessThanComparable;
269 namespace traits_detail_IsNothrowSwappable {
270 #if defined(_MSC_VER) || defined(__cpp_lib_is_swappable)
271 // MSVC already implements the C++17 P0185R1 proposal which
272 // adds std::is_nothrow_swappable, so use it instead.
273 template <typename T>
274 using IsNothrowSwappable = std::is_nothrow_swappable<T>;
276 /* using override */ using std::swap;
279 struct IsNothrowSwappable
280 : std::integral_constant<bool,
281 std::is_nothrow_move_constructible<T>::value &&
282 noexcept(swap(std::declval<T&>(), std::declval<T&>()))
287 /* using override */ using traits_detail_IsNothrowSwappable::IsNothrowSwappable;
289 template <class T> struct IsTriviallyCopyable
291 traits_detail::has_IsTriviallyCopyable<T>::value,
292 traits_detail::has_true_IsTriviallyCopyable<T>,
293 traits_detail::is_trivially_copyable<T>
296 template <class T> struct IsRelocatable
298 traits_detail::has_IsRelocatable<T>::value,
299 traits_detail::has_true_IsRelocatable<T>,
300 // TODO add this line (and some tests for it) when we upgrade to gcc 4.7
301 //std::is_trivially_move_constructible<T>::value ||
302 IsTriviallyCopyable<T>
305 template <class T> struct IsZeroInitializable
307 traits_detail::has_IsZeroInitializable<T>::value,
308 traits_detail::has_true_IsZeroInitializable<T>,
309 std::integral_constant<bool, !std::is_class<T>::value>
312 template <typename...>
313 struct Conjunction : std::true_type {};
314 template <typename T>
315 struct Conjunction<T> : T {};
316 template <typename T, typename... TList>
317 struct Conjunction<T, TList...>
318 : std::conditional<T::value, Conjunction<TList...>, T>::type {};
320 template <typename...>
321 struct Disjunction : std::false_type {};
322 template <typename T>
323 struct Disjunction<T> : T {};
324 template <typename T, typename... TList>
325 struct Disjunction<T, TList...>
326 : std::conditional<T::value, T, Disjunction<TList...>>::type {};
328 template <typename T>
329 struct Negation : std::integral_constant<bool, !T::value> {};
331 template <bool... Bs>
333 using valid_type = bool;
334 static constexpr std::size_t size() {
335 return sizeof...(Bs);
339 // Lighter-weight than Conjunction, but evaluates all sub-conditions eagerly.
340 template <class... Ts>
341 using StrictConjunction =
342 std::is_same<Bools<Ts::value..., true>, Bools<true, Ts::value...>>;
347 * Use this macro ONLY inside namespace folly. When using it with a
348 * regular type, use it like this:
350 * // Make sure you're at namespace ::folly scope
351 * template<> FOLLY_ASSUME_RELOCATABLE(MyType)
353 * When using it with a template type, use it like this:
355 * // Make sure you're at namespace ::folly scope
356 * template<class T1, class T2>
357 * FOLLY_ASSUME_RELOCATABLE(MyType<T1, T2>)
359 #define FOLLY_ASSUME_RELOCATABLE(...) \
360 struct IsRelocatable< __VA_ARGS__ > : std::true_type {};
363 * The FOLLY_ASSUME_FBVECTOR_COMPATIBLE* macros below encode the
364 * assumption that the type is relocatable per IsRelocatable
365 * above. Many types can be assumed to satisfy this condition, but
366 * it is the responsibility of the user to state that assumption.
367 * User-defined classes will not be optimized for use with
368 * fbvector (see FBVector.h) unless they state that assumption.
370 * Use FOLLY_ASSUME_FBVECTOR_COMPATIBLE with regular types like this:
372 * FOLLY_ASSUME_FBVECTOR_COMPATIBLE(MyType)
374 * The versions FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1, _2, _3, and _4
375 * allow using the macro for describing templatized classes with 1, 2,
376 * 3, and 4 template parameters respectively. For template classes
377 * just use the macro with the appropriate number and pass the name of
378 * the template to it. Example:
380 * template <class T1, class T2> class MyType { ... };
382 * // Make sure you're at global scope
383 * FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(MyType)
386 // Use this macro ONLY at global level (no namespace)
387 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE(...) \
390 FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__) \
392 // Use this macro ONLY at global level (no namespace)
393 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(...) \
395 template <class T1> \
396 FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1>) \
398 // Use this macro ONLY at global level (no namespace)
399 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(...) \
401 template <class T1, class T2> \
402 FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1, T2>) \
404 // Use this macro ONLY at global level (no namespace)
405 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(...) \
407 template <class T1, class T2, class T3> \
408 FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1, T2, T3>) \
410 // Use this macro ONLY at global level (no namespace)
411 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_4(...) \
413 template <class T1, class T2, class T3, class T4> \
414 FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1, T2, T3, T4>) \
418 * Instantiate FOLLY_ASSUME_FBVECTOR_COMPATIBLE for a few types. It is
419 * safe to assume that pair is compatible if both of its components
420 * are. Furthermore, all STL containers can be assumed to comply,
421 * although that is not guaranteed by the standard.
424 FOLLY_NAMESPACE_STD_BEGIN
426 template <class T, class U>
428 #ifndef _GLIBCXX_USE_FB
429 FOLLY_GLIBCXX_NAMESPACE_CXX11_BEGIN
430 template <class T, class R, class A>
432 FOLLY_GLIBCXX_NAMESPACE_CXX11_END
434 template <class T, class R, class A, class S>
437 template <class T, class A>
439 template <class T, class A>
441 FOLLY_GLIBCXX_NAMESPACE_CXX11_BEGIN
442 template <class T, class A>
444 FOLLY_GLIBCXX_NAMESPACE_CXX11_END
445 template <class T, class C, class A>
447 template <class K, class V, class C, class A>
452 FOLLY_NAMESPACE_STD_END
456 // STL commonly-used types
457 template <class T, class U>
458 struct IsRelocatable< std::pair<T, U> >
459 : std::integral_constant<bool,
460 IsRelocatable<T>::value &&
461 IsRelocatable<U>::value> {};
463 // Is T one of T1, T2, ..., Tn?
464 template <class T, class... Ts>
466 enum { value = false };
469 template <class T, class T1, class... Ts>
470 struct IsOneOf<T, T1, Ts...> {
471 enum { value = std::is_same<T, T1>::value || IsOneOf<T, Ts...>::value };
475 * Complementary type traits for integral comparisons.
477 * For instance, `if(x < 0)` yields an error in clang for unsigned types
478 * when -Werror is used due to -Wtautological-compare
481 * @author: Marcelo Juchem <marcelo@fb.com>
486 template <typename T, bool>
487 struct is_negative_impl {
488 constexpr static bool check(T x) { return x < 0; }
491 template <typename T>
492 struct is_negative_impl<T, false> {
493 constexpr static bool check(T) { return false; }
496 // folly::to integral specializations can end up generating code
497 // inside what are really static ifs (not executed because of the templated
498 // types) that violate -Wsign-compare and/or -Wbool-compare so suppress them
499 // in order to not prevent all calling code from using it.
501 FOLLY_GCC_DISABLE_WARNING(sign-compare)
502 #if __GNUC_PREREQ(5, 0)
503 FOLLY_GCC_DISABLE_WARNING(bool-compare)
505 FOLLY_MSVC_DISABLE_WARNING(4388) // sign-compare
506 FOLLY_MSVC_DISABLE_WARNING(4804) // bool-compare
508 template <typename RHS, RHS rhs, typename LHS>
509 bool less_than_impl(LHS const lhs) {
511 rhs > std::numeric_limits<LHS>::max() ? true :
512 rhs <= std::numeric_limits<LHS>::min() ? false :
516 template <typename RHS, RHS rhs, typename LHS>
517 bool greater_than_impl(LHS const lhs) {
519 rhs > std::numeric_limits<LHS>::max() ? false :
520 rhs < std::numeric_limits<LHS>::min() ? true :
526 } // namespace detail {
529 template <typename T>
530 constexpr bool is_negative(T x) {
531 return folly::detail::is_negative_impl<T, std::is_signed<T>::value>::check(x);
535 template <typename T>
536 constexpr bool is_non_positive(T x) { return !x || folly::is_negative(x); }
539 template <typename T>
540 constexpr bool is_positive(T x) { return !is_non_positive(x); }
543 template <typename T>
544 constexpr bool is_non_negative(T x) {
545 return !x || is_positive(x);
548 template <typename RHS, RHS rhs, typename LHS>
549 bool less_than(LHS const lhs) {
550 return detail::less_than_impl<
551 RHS, rhs, typename std::remove_reference<LHS>::type
555 template <typename RHS, RHS rhs, typename LHS>
556 bool greater_than(LHS const lhs) {
557 return detail::greater_than_impl<
558 RHS, rhs, typename std::remove_reference<LHS>::type
562 namespace traits_detail {
563 struct InPlaceTag {};
565 struct InPlaceTypeTag {};
566 template <std::size_t>
567 struct InPlaceIndexTag {};
571 * Like std::piecewise_construct, a tag type & instance used for in-place
572 * construction of non-movable contained types, e.g. by Synchronized.
573 * Follows the naming and design of std::in_place suggested in
574 * http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0032r2.pdf
576 using in_place_t = traits_detail::InPlaceTag (&)(traits_detail::InPlaceTag);
579 using in_place_type_t =
580 traits_detail::InPlaceTypeTag<T> (&)(traits_detail::InPlaceTypeTag<T>);
582 template <std::size_t I>
583 using in_place_index_t =
584 traits_detail::InPlaceIndexTag<I> (&)(traits_detail::InPlaceIndexTag<I>);
586 inline traits_detail::InPlaceTag in_place(traits_detail::InPlaceTag = {}) {
591 inline traits_detail::InPlaceTypeTag<T> in_place(
592 traits_detail::InPlaceTypeTag<T> = {}) {
596 template <std::size_t I>
597 inline traits_detail::InPlaceIndexTag<I> in_place(
598 traits_detail::InPlaceIndexTag<I> = {}) {
602 // For backwards compatibility:
603 using construct_in_place_t = in_place_t;
605 inline traits_detail::InPlaceTag construct_in_place(
606 traits_detail::InPlaceTag = {}) {
611 * Initializer lists are a powerful compile time syntax introduced in C++11
612 * but due to their often conflicting syntax they are not used by APIs for
615 * Further standard conforming compilers *strongly* favor an
616 * std::initalizer_list overload for construction if one exists. The
617 * following is a simple tag used to disambiguate construction with
618 * initializer lists and regular uniform initialization.
620 * For example consider the following case
624 * explicit Something(int);
625 * Something(std::intiializer_list<int>);
631 * Something something{1}; // SURPRISE!!
633 * The last call to instantiate the Something object will go to the
634 * initializer_list overload. Which may be surprising to users.
636 * If however this tag was used to disambiguate such construction it would be
637 * easy for users to see which construction overload their code was referring
642 * explicit Something(int);
643 * Something(folly::initlist_construct_t, std::initializer_list<int>);
649 * Something something_one{1}; // not the initializer_list overload
650 * Something something_two{folly::initlist_construct, {1}}; // correct
652 struct initlist_construct_t {};
653 constexpr initlist_construct_t initlist_construct{};
657 // Assume nothing when compiling with MSVC.
659 // gcc-5.0 changed string's implementation in libgcc to be non-relocatable
661 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(std::basic_string)
663 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::vector)
664 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::list)
665 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::deque)
666 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::unique_ptr)
667 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(std::shared_ptr)
668 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(std::function)
671 /* Some combinations of compilers and C++ libraries make __int128 and
672 * unsigned __int128 available but do not correctly define their standard type
675 * If FOLLY_SUPPLY_MISSING_INT128_TRAITS is defined, we define these traits
678 * @author: Phil Willoughby <philwill@fb.com>
680 #if FOLLY_SUPPLY_MISSING_INT128_TRAITS
681 FOLLY_NAMESPACE_STD_BEGIN
683 struct is_arithmetic<__int128> : ::std::true_type {};
685 struct is_arithmetic<unsigned __int128> : ::std::true_type {};
687 struct is_integral<__int128> : ::std::true_type {};
689 struct is_integral<unsigned __int128> : ::std::true_type {};
691 struct make_unsigned<__int128> {
692 typedef unsigned __int128 type;
695 struct make_signed<__int128> {
696 typedef __int128 type;
699 struct make_unsigned<unsigned __int128> {
700 typedef unsigned __int128 type;
703 struct make_signed<unsigned __int128> {
704 typedef __int128 type;
707 struct is_signed<__int128> : ::std::true_type {};
709 struct is_unsigned<unsigned __int128> : ::std::true_type {};
710 FOLLY_NAMESPACE_STD_END
711 #endif // FOLLY_SUPPLY_MISSING_INT128_TRAITS