static.hpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*=============================================================================
  2. Copyright (c) 2014 Paul Fultz II
  3. static.h
  4. Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. ==============================================================================*/
  7. #ifndef BOOST_HOF_GUARD_FUNCTION_STATIC_H
  8. #define BOOST_HOF_GUARD_FUNCTION_STATIC_H
  9. /// static
  10. /// ======
  11. ///
  12. /// Description
  13. /// -----------
  14. ///
  15. /// The `static_` adaptor is a static function adaptor that allows any
  16. /// default-constructible function object to be static-initialized. Functions
  17. /// initialized by `static_` cannot be used in `constexpr` functions. If the
  18. /// function needs to be statically initialized and called in a `constexpr`
  19. /// context, then a `constexpr` constructor needs to be used rather than
  20. /// `static_`.
  21. ///
  22. /// Synopsis
  23. /// --------
  24. ///
  25. /// template<class F>
  26. /// class static_;
  27. ///
  28. /// Requirements
  29. /// ------------
  30. ///
  31. /// F must be:
  32. ///
  33. /// * [ConstFunctionObject](ConstFunctionObject)
  34. /// * DefaultConstructible
  35. ///
  36. /// Example
  37. /// -------
  38. ///
  39. /// #include <boost/hof.hpp>
  40. /// #include <cassert>
  41. /// using namespace boost::hof;
  42. ///
  43. /// // In C++ this class can't be static-initialized, because of the non-
  44. /// // trivial default constructor.
  45. /// struct times_function
  46. /// {
  47. /// double factor;
  48. /// times_function() : factor(2)
  49. /// {}
  50. /// template<class T>
  51. /// T operator()(T x) const
  52. /// {
  53. /// return x*factor;
  54. /// }
  55. /// };
  56. ///
  57. /// static constexpr static_<times_function> times2 = {};
  58. ///
  59. /// int main() {
  60. /// assert(6 == times2(3));
  61. /// }
  62. ///
  63. #include <boost/hof/detail/result_of.hpp>
  64. #include <boost/hof/reveal.hpp>
  65. namespace boost { namespace hof {
  66. template<class F>
  67. struct static_
  68. {
  69. struct failure
  70. : failure_for<F>
  71. {};
  72. const F& base_function() const
  73. BOOST_HOF_NOEXCEPT_CONSTRUCTIBLE(F)
  74. {
  75. static F f;
  76. return f;
  77. }
  78. BOOST_HOF_RETURNS_CLASS(static_);
  79. template<class... Ts>
  80. BOOST_HOF_SFINAE_RESULT(F, id_<Ts>...)
  81. operator()(Ts && ... xs) const
  82. BOOST_HOF_SFINAE_RETURNS(BOOST_HOF_CONST_THIS->base_function()(BOOST_HOF_FORWARD(Ts)(xs)...));
  83. };
  84. }} // namespace boost::hof
  85. #endif