unsafe_declval.hpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright (c) 2019-2024 Antony Polukhin.
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef BOOST_PFR_DETAIL_UNSAFE_DECLVAL_HPP
  6. #define BOOST_PFR_DETAIL_UNSAFE_DECLVAL_HPP
  7. #pragma once
  8. #include <boost/pfr/detail/config.hpp>
  9. #include <type_traits>
  10. namespace boost { namespace pfr { namespace detail {
  11. // This function serves as a link-time assert. If linker requires it, then
  12. // `unsafe_declval()` is used at runtime.
  13. void report_if_you_see_link_error_with_this_function() noexcept;
  14. // For returning non default constructible types. Do NOT use at runtime!
  15. //
  16. // GCCs std::declval may not be used in potentionally evaluated contexts,
  17. // so we reinvent it.
  18. template <class T>
  19. constexpr T unsafe_declval() noexcept {
  20. report_if_you_see_link_error_with_this_function();
  21. typename std::remove_reference<T>::type* ptr = nullptr;
  22. ptr += 42; // suppresses 'null pointer dereference' warnings
  23. return static_cast<T>(*ptr);
  24. }
  25. }}} // namespace boost::pfr::detail
  26. #endif // BOOST_PFR_DETAIL_UNSAFE_DECLVAL_HPP