static_const_var.hpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*=============================================================================
  2. Copyright (c) 2015 Paul Fultz II
  3. static_const_var.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_STATIC_CONST_H
  8. #define BOOST_HOF_GUARD_STATIC_CONST_H
  9. #include <boost/hof/detail/intrinsics.hpp>
  10. namespace boost { namespace hof { namespace detail {
  11. template<class T>
  12. struct static_const_storage
  13. {
  14. static constexpr T value = T();
  15. };
  16. template<class T>
  17. constexpr T static_const_storage<T>::value;
  18. struct static_const_var_factory
  19. {
  20. constexpr static_const_var_factory()
  21. {}
  22. template<class T>
  23. constexpr const T& operator=(const T&) const
  24. {
  25. static_assert(BOOST_HOF_IS_DEFAULT_CONSTRUCTIBLE(T), "Static const variable must be default constructible");
  26. return static_const_storage<T>::value;
  27. }
  28. };
  29. }
  30. template<class T>
  31. constexpr const T& static_const_var()
  32. {
  33. return detail::static_const_storage<T>::value;
  34. }
  35. }} // namespace boost::hof
  36. #if BOOST_HOF_HAS_RELAXED_CONSTEXPR || defined(_MSC_VER)
  37. #define BOOST_HOF_STATIC_CONSTEXPR const constexpr
  38. #else
  39. #define BOOST_HOF_STATIC_CONSTEXPR static constexpr
  40. #endif
  41. #if defined(__GNUC__) && !defined (__clang__) && __GNUC__ == 4 && __GNUC_MINOR__ < 7
  42. #define BOOST_HOF_STATIC_AUTO_REF extern __attribute__((weak)) constexpr auto
  43. #else
  44. #define BOOST_HOF_STATIC_AUTO_REF static constexpr auto&
  45. #endif
  46. // On gcc 4.6 use weak variables
  47. #if defined(__GNUC__) && !defined (__clang__) && __GNUC__ == 4 && __GNUC_MINOR__ < 7
  48. #define BOOST_HOF_STATIC_CONST_VAR(name) extern __attribute__((weak)) constexpr auto name
  49. #else
  50. #define BOOST_HOF_STATIC_CONST_VAR(name) static constexpr auto& name = boost::hof::detail::static_const_var_factory()
  51. #endif
  52. #define BOOST_HOF_DECLARE_STATIC_VAR(name, ...) BOOST_HOF_STATIC_CONST_VAR(name) = __VA_ARGS__{}
  53. #endif