Unit.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright 2015-present 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. #pragma once
  17. #include <type_traits>
  18. namespace folly {
  19. /// In functional programming, the degenerate case is often called "unit". In
  20. /// C++, "void" is often the best analogue. However, because of the syntactic
  21. /// special-casing required for void, it is frequently a liability for template
  22. /// metaprogramming. So, instead of writing specializations to handle cases like
  23. /// SomeContainer<void>, a library author may instead rule that out and simply
  24. /// have library users use SomeContainer<Unit>. Contained values may be ignored.
  25. /// Much easier.
  26. ///
  27. /// "void" is the type that admits of no values at all. It is not possible to
  28. /// construct a value of this type.
  29. /// "unit" is the type that admits of precisely one unique value. It is
  30. /// possible to construct a value of this type, but it is always the same value
  31. /// every time, so it is uninteresting.
  32. struct Unit {
  33. constexpr bool operator==(const Unit& /*other*/) const {
  34. return true;
  35. }
  36. constexpr bool operator!=(const Unit& /*other*/) const {
  37. return false;
  38. }
  39. };
  40. constexpr Unit unit{};
  41. template <typename T>
  42. struct lift_unit {
  43. using type = T;
  44. };
  45. template <>
  46. struct lift_unit<void> {
  47. using type = Unit;
  48. };
  49. template <typename T>
  50. using lift_unit_t = typename lift_unit<T>::type;
  51. template <typename T>
  52. struct drop_unit {
  53. using type = T;
  54. };
  55. template <>
  56. struct drop_unit<Unit> {
  57. using type = void;
  58. };
  59. template <typename T>
  60. using drop_unit_t = typename drop_unit<T>::type;
  61. } // namespace folly