move assignment operators for folly::Synchronized
[folly.git] / folly / Traits.h
1 /*
2  * Copyright 2013 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 // @author: Andrei Alexandrescu
18
19 #ifndef FOLLY_BASE_TRAITS_H_
20 #define FOLLY_BASE_TRAITS_H_
21
22 #include <memory>
23 #include <limits>
24 #include <type_traits>
25
26 #include <bits/c++config.h>
27
28 #include <boost/type_traits.hpp>
29 #include <boost/mpl/and.hpp>
30 #include <boost/mpl/has_xxx.hpp>
31 #include <boost/mpl/not.hpp>
32
33 namespace folly {
34
35 /**
36  * IsRelocatable<T>::value describes the ability of moving around
37  * memory a value of type T by using memcpy (as opposed to the
38  * conservative approach of calling the copy constructor and then
39  * destroying the old temporary. Essentially for a relocatable type,
40  * the following two sequences of code should be semantically
41  * equivalent:
42  *
43  * void move1(T * from, T * to) {
44  *   new(to) T(from);
45  *   (*from).~T();
46  * }
47  *
48  * void move2(T * from, T * to) {
49  *   memcpy(to, from, sizeof(T));
50  * }
51  *
52  * Most C++ types are relocatable; the ones that aren't would include
53  * internal pointers or (very rarely) would need to update remote
54  * pointers to pointers tracking them. All C++ primitive types and
55  * type constructors are relocatable.
56  *
57  * This property can be used in a variety of optimizations. Currently
58  * fbvector uses this property intensively.
59  *
60  * The default conservatively assumes the type is not
61  * relocatable. Several specializations are defined for known
62  * types. You may want to add your own specializations. Do so in
63  * namespace folly and make sure you keep the specialization of
64  * IsRelocatable<SomeStruct> in the same header as SomeStruct.
65  *
66  * You may also declare a type to be relocatable by including
67  *    `typedef std::true_type IsRelocatable;`
68  * in the class header.
69  *
70  * It may be unset in a base class by overriding the typedef to false_type.
71  */
72 /*
73  * IsTriviallyCopyable describes the value semantics property. C++11 contains
74  * the type trait is_trivially_copyable; however, it is not yet implemented
75  * in gcc (as of 4.7.1), and the user may wish to specify otherwise.
76  */
77 /*
78  * IsZeroInitializable describes the property that default construction is the
79  * same as memset(dst, 0, sizeof(T)).
80  */
81
82 namespace traits_detail {
83
84 #define FOLLY_HAS_TRUE_XXX(name)                          \
85   BOOST_MPL_HAS_XXX_TRAIT_DEF(name);                      \
86   template <class T> struct name ## _is_true              \
87     : std::is_same<typename T::name, std::true_type> {};  \
88   template <class T> struct has_true_ ## name             \
89     : std::conditional<                                   \
90         has_ ## name <T>::value,                          \
91         name ## _is_true<T>,                              \
92         std::false_type                                   \
93       >:: type {};
94
95 FOLLY_HAS_TRUE_XXX(IsRelocatable)
96 FOLLY_HAS_TRUE_XXX(IsZeroInitializable)
97 FOLLY_HAS_TRUE_XXX(IsTriviallyCopyable)
98
99 #undef FOLLY_HAS_TRUE_XXX
100 }
101
102 template <class T> struct IsTriviallyCopyable
103   : std::integral_constant<bool,
104       !std::is_class<T>::value ||
105       // TODO: add alternate clause is_trivially_copyable, when available
106       traits_detail::has_true_IsTriviallyCopyable<T>::value
107     > {};
108
109 template <class T> struct IsRelocatable
110   : std::integral_constant<bool,
111       !std::is_class<T>::value ||
112       // TODO add this line (and some tests for it) when we upgrade to gcc 4.7
113       //std::is_trivially_move_constructible<T>::value ||
114       IsTriviallyCopyable<T>::value ||
115       traits_detail::has_true_IsRelocatable<T>::value
116     > {};
117
118 template <class T> struct IsZeroInitializable
119   : std::integral_constant<bool,
120       !std::is_class<T>::value ||
121       traits_detail::has_true_IsZeroInitializable<T>::value
122     > {};
123
124 } // namespace folly
125
126 /**
127  * Use this macro ONLY inside namespace folly. When using it with a
128  * regular type, use it like this:
129  *
130  * // Make sure you're at namespace ::folly scope
131  * template<> FOLLY_ASSUME_RELOCATABLE(MyType)
132  *
133  * When using it with a template type, use it like this:
134  *
135  * // Make sure you're at namespace ::folly scope
136  * template<class T1, class T2>
137  * FOLLY_ASSUME_RELOCATABLE(MyType<T1, T2>)
138  */
139 #define FOLLY_ASSUME_RELOCATABLE(...) \
140   struct IsRelocatable<  __VA_ARGS__ > : std::true_type {};
141
142 /**
143  * Use this macro ONLY inside namespace boost. When using it with a
144  * regular type, use it like this:
145  *
146  * // Make sure you're at namespace ::boost scope
147  * template<> FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(MyType)
148  *
149  * When using it with a template type, use it like this:
150  *
151  * // Make sure you're at namespace ::boost scope
152  * template<class T1, class T2>
153  * FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(MyType<T1, T2>)
154  */
155 #define FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(...) \
156   struct has_nothrow_constructor<  __VA_ARGS__ > : ::boost::true_type {};
157
158 /**
159  * The FOLLY_ASSUME_FBVECTOR_COMPATIBLE* macros below encode two
160  * assumptions: first, that the type is relocatable per IsRelocatable
161  * above, and that it has a nothrow constructor. Most types can be
162  * assumed to satisfy both conditions, but it is the responsibility of
163  * the user to state that assumption. User-defined classes will not
164  * work with fbvector (see FBVector.h) unless they state this
165  * combination of properties.
166  *
167  * Use FOLLY_ASSUME_FBVECTOR_COMPATIBLE with regular types like this:
168  *
169  * FOLLY_ASSUME_FBVECTOR_COMPATIBLE(MyType)
170  *
171  * The versions FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1, _2, _3, and _4
172  * allow using the macro for describing templatized classes with 1, 2,
173  * 3, and 4 template parameters respectively. For template classes
174  * just use the macro with the appropriate number and pass the name of
175  * the template to it. Example:
176  *
177  * template <class T1, class T2> class MyType { ... };
178  * ...
179  * // Make sure you're at global scope
180  * FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(MyType)
181  */
182
183 // Use this macro ONLY at global level (no namespace)
184 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE(...)                           \
185   namespace folly { template<> FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__) }   \
186   namespace boost { \
187   template<> FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__) }
188 // Use this macro ONLY at global level (no namespace)
189 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(...)                         \
190   namespace folly {                                                     \
191   template <class T1> FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1>) }       \
192     namespace boost {                                                   \
193     template <class T1> FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__<T1>) }
194 // Use this macro ONLY at global level (no namespace)
195 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(...)                 \
196   namespace folly {                                             \
197   template <class T1, class T2>                                 \
198   FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1, T2>) }               \
199     namespace boost {                                           \
200     template <class T1, class T2>                               \
201     FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__<T1, T2>) }
202 // Use this macro ONLY at global level (no namespace)
203 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(...)                         \
204   namespace folly {                                                     \
205   template <class T1, class T2, class T3>                               \
206   FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1, T2, T3>) }                   \
207     namespace boost {                                                   \
208     template <class T1, class T2, class T3>                             \
209     FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__<T1, T2, T3>) }
210 // Use this macro ONLY at global level (no namespace)
211 #define FOLLY_ASSUME_FBVECTOR_COMPATIBLE_4(...)                         \
212   namespace folly {                                                     \
213   template <class T1, class T2, class T3, class T4>                     \
214   FOLLY_ASSUME_RELOCATABLE(__VA_ARGS__<T1, T2, T3, T4>) }               \
215     namespace boost {                                                   \
216     template <class T1, class T2, class T3, class T4>                   \
217     FOLLY_ASSUME_HAS_NOTHROW_CONSTRUCTOR(__VA_ARGS__<T1, T2, T3, T4>) }
218
219 /**
220  * Instantiate FOLLY_ASSUME_FBVECTOR_COMPATIBLE for a few types. It is
221  * safe to assume that pair is compatible if both of its components
222  * are. Furthermore, all STL containers can be assumed to comply,
223  * although that is not guaranteed by the standard.
224  */
225
226 namespace std {
227
228 template <class T, class U>
229   struct pair;
230 #ifndef _GLIBCXX_USE_FB
231 template <class T, class R, class A>
232   class basic_string;
233 #else
234 template <class T, class R, class A, class S>
235   class basic_string;
236 #endif
237 template <class T, class A>
238   class vector;
239 template <class T, class A>
240   class deque;
241 template <class T, class A>
242   class list;
243 template <class T, class C, class A>
244   class set;
245 template <class K, class V, class C, class A>
246   class map;
247 template <class T>
248   class shared_ptr;
249
250 }
251
252 namespace boost {
253
254 template <class T> class shared_ptr;
255
256 template <class T, class U>
257 struct has_nothrow_constructor< std::pair<T, U> >
258     : ::boost::mpl::and_< has_nothrow_constructor<T>,
259                           has_nothrow_constructor<U> > {};
260
261 } // namespace boost
262
263 namespace folly {
264
265 // STL commonly-used types
266 template <class T, class U>
267 struct IsRelocatable<  std::pair<T, U> >
268     : ::boost::mpl::and_< IsRelocatable<T>, IsRelocatable<U> > {};
269
270 // Is T one of T1, T2, ..., Tn?
271 template <class T, class... Ts>
272 struct IsOneOf {
273   enum { value = false };
274 };
275
276 template <class T, class T1, class... Ts>
277 struct IsOneOf<T, T1, Ts...> {
278   enum { value = std::is_same<T, T1>::value || IsOneOf<T, Ts...>::value };
279 };
280
281 /**
282  * A traits class to check for incomplete types.
283  *
284  * Example:
285  *
286  *  struct FullyDeclared {}; // complete type
287  *  struct ForwardDeclared; // incomplete type
288  *
289  *  is_complete<int>::value // evaluates to true
290  *  is_complete<FullyDeclared>::value // evaluates to true
291  *  is_complete<ForwardDeclared>::value // evaluates to false
292  *
293  *  struct ForwardDeclared {}; // declared, at last
294  *
295  *  is_complete<ForwardDeclared>::value // now it evaluates to true
296  *
297  * @author: Marcelo Juchem <marcelo@fb.com>
298  */
299 template <typename T>
300 class is_complete {
301   template <unsigned long long> struct sfinae {};
302   template <typename U>
303   constexpr static bool test(sfinae<sizeof(U)>*) { return true; }
304   template <typename> constexpr static bool test(...) { return false; }
305 public:
306   constexpr static bool value = test<T>(nullptr);
307 };
308
309 /*
310  * Complementary type traits for integral comparisons.
311  *
312  * For instance, `if(x < 0)` yields an error in clang for unsigned types
313  *  when -Werror is used due to -Wtautological-compare
314  *
315  *
316  * @author: Marcelo Juchem <marcelo@fb.com>
317  */
318
319 namespace detail {
320
321 template <typename T, bool>
322 struct is_negative_impl {
323   constexpr static bool check(T x) { return x < 0; }
324 };
325
326 template <typename T>
327 struct is_negative_impl<T, false> {
328   constexpr static bool check(T x) { return false; }
329 };
330
331 template <typename RHS, RHS rhs, typename LHS>
332 bool less_than_impl(
333   typename std::enable_if<
334     (rhs <= std::numeric_limits<LHS>::max()
335       && rhs > std::numeric_limits<LHS>::min()),
336     LHS
337   >::type const lhs
338 ) {
339   return lhs < rhs;
340 }
341
342 template <typename RHS, RHS rhs, typename LHS>
343 bool less_than_impl(
344   typename std::enable_if<
345     (rhs > std::numeric_limits<LHS>::max()),
346     LHS
347   >::type const
348 ) {
349   return true;
350 }
351
352 template <typename RHS, RHS rhs, typename LHS>
353 bool less_than_impl(
354   typename std::enable_if<
355     (rhs <= std::numeric_limits<LHS>::min()),
356     LHS
357   >::type const
358 ) {
359   return false;
360 }
361
362 template <typename RHS, RHS rhs, typename LHS>
363 bool greater_than_impl(
364   typename std::enable_if<
365     (rhs <= std::numeric_limits<LHS>::max()
366       && rhs >= std::numeric_limits<LHS>::min()),
367     LHS
368   >::type const lhs
369 ) {
370   return lhs > rhs;
371 }
372
373 template <typename RHS, RHS rhs, typename LHS>
374 bool greater_than_impl(
375   typename std::enable_if<
376     (rhs > std::numeric_limits<LHS>::max()),
377     LHS
378   >::type const
379 ) {
380   return false;
381 }
382
383 template <typename RHS, RHS rhs, typename LHS>
384 bool greater_than_impl(
385   typename std::enable_if<
386     (rhs < std::numeric_limits<LHS>::min()),
387     LHS
388   >::type const
389 ) {
390   return true;
391 }
392
393 } // namespace detail {
394
395 // same as `x < 0`
396 template <typename T>
397 constexpr bool is_negative(T x) {
398   return folly::detail::is_negative_impl<T, std::is_signed<T>::value>::check(x);
399 }
400
401 // same as `x <= 0`
402 template <typename T>
403 constexpr bool is_non_positive(T x) { return !x || folly::is_negative(x); }
404
405 template <typename RHS, RHS rhs, typename LHS>
406 bool less_than(LHS const lhs) {
407   return detail::less_than_impl<
408     RHS, rhs, typename std::remove_reference<LHS>::type
409   >(lhs);
410 }
411
412 template <typename RHS, RHS rhs, typename LHS>
413 bool greater_than(LHS const lhs) {
414   return detail::greater_than_impl<
415     RHS, rhs, typename std::remove_reference<LHS>::type
416   >(lhs);
417 }
418
419 } // namespace folly
420
421 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(std::basic_string);
422 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::vector);
423 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::list);
424 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::deque);
425 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_4(std::map);
426 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_3(std::set);
427 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_2(std::unique_ptr);
428 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(std::shared_ptr);
429 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(std::function);
430
431 // Boost
432 FOLLY_ASSUME_FBVECTOR_COMPATIBLE_1(boost::shared_ptr);
433
434 #define FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, cv_qual) \
435   template <typename TTheClass_, typename RTheReturn_, typename... TTheArgs_> \
436   class classname<TTheClass_, RTheReturn_(TTheArgs_...) cv_qual> { \
437     template < \
438       typename UTheClass_, RTheReturn_ (UTheClass_::*)(TTheArgs_...) cv_qual \
439     > struct sfinae {}; \
440     template <typename UTheClass_> \
441     constexpr static bool test(sfinae<UTheClass_, &UTheClass_::func_name>*) \
442     { return true; } \
443     template <typename> \
444     constexpr static bool test(...) { return false; } \
445   public: \
446     constexpr static bool value = test<TTheClass_>(nullptr); \
447   }
448
449 /*
450  * The FOLLY_CREATE_HAS_MEMBER_FN_TRAITS is used to create traits
451  * classes that check for the existence of a member function with
452  * a given name and signature. It currently does not support
453  * checking for inherited members.
454  *
455  * Such classes receive two template parameters: the class to be checked
456  * and the signature of the member function. A static boolean field
457  * named `value` (which is also constexpr) tells whether such member
458  * function exists.
459  *
460  * Each traits class created is bound only to the member name, not to
461  * its signature nor to the type of the class containing it.
462  *
463  * Say you need to know if a given class has a member function named
464  * `test` with the following signature:
465  *
466  *    int test() const;
467  *
468  * You'd need this macro to create a traits class to check for a member
469  * named `test`, and then use this traits class to check for the signature:
470  *
471  * namespace {
472  *
473  * FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(has_test_traits, test);
474  *
475  * } // unnamed-namespace
476  *
477  * void some_func() {
478  *   cout << "Does class Foo have a member int test() const? "
479  *     << boolalpha << has_test_traits<Foo, int() const>::value;
480  * }
481  *
482  * You can use the same traits class to test for a completely different
483  * signature, on a completely different class, as long as the member name
484  * is the same:
485  *
486  * void some_func() {
487  *   cout << "Does class Foo have a member int test()? "
488  *     << boolalpha << has_test_traits<Foo, int()>::value;
489  *   cout << "Does class Foo have a member int test() const? "
490  *     << boolalpha << has_test_traits<Foo, int() const>::value;
491  *   cout << "Does class Bar have a member double test(const string&, long)? "
492  *     << boolalpha << has_test_traits<Bar, double(const string&, long)>::value;
493  * }
494  *
495  * @author: Marcelo Juchem <marcelo@fb.com>
496  */
497 #define FOLLY_CREATE_HAS_MEMBER_FN_TRAITS(classname, func_name) \
498   template <typename, typename> class classname; \
499   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, ); \
500   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, const); \
501   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, volatile); \
502   FOLLY_CREATE_HAS_MEMBER_FN_TRAITS_IMPL(classname, func_name, volatile const)
503
504 #endif //FOLLY_BASE_TRAITS_H_