/
anenkov
/
CppUtils
Обзор
Документация
Войти
/
anenkov
/
CppUtils
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
utils.hpp
68 строк
2 KB
Aleksandr Anenkov
Fix exception type
01 авг 2024, 01:25
01 авг 2024, 01:25
f12b5f4
Код
Авторство
О чём код?
#include <source_location> #include <stdexcept> #include <string> #include <ranges> #define throw_with_message_if_not(cond, msg) \ if (cond) [[likely]] \ static_cast<void>(0); \ else \ std::throw_with_nested(std::logic_error(msg)) \ #define throw_if_not(cond) \ throw_with_message_if_not(cond, "Condition failed: "#cond" in " + std::string(std::source_location::current().function_name())); namespace utils { template <class R, class V> concept view_of = std::ranges::input_range<R> && (std::same_as<std::ranges::range_value_t<R>, V> || std::convertible_to<std::ranges::range_value_t<R>, const V&>); template <class T> concept is_comparable_to_pointer = requires(T a) { { std::declval<T>() != nullptr }; }; template <class T> class not_null { public: static_assert(is_comparable_to_pointer<T>, "Type is not convertibe to a pointer"); constexpr not_null(std::nullptr_t) = delete; constexpr not_null& operator=(std::nullptr_t) = delete; constexpr not_null(const not_null<T>&) = default; constexpr not_null(not_null<T>&&) noexcept(std::is_nothrow_move_constructible_v<not_null<T>>) = default; constexpr not_null& operator=(const not_null<T>&) = default; constexpr not_null& operator=(not_null<T>&&) noexcept = default; constexpr not_null(T t) : m_ptr{std::forward<T>(t)} { check(); } template <class U> requires (std::is_convertible_v<T, U>) constexpr not_null(U u) : m_ptr{std::forward<U>(u)} { check(); } [[nodiscard]] constexpr T get() const noexcept { return m_ptr; } constexpr operator T() const { return get(); } constexpr auto operator->() const { return get(); } [[nodiscard]] constexpr auto operator*() const { return *get(); } private: T m_ptr; constexpr void check() const { if (!m_ptr) [[unlikely]] { throw std::logic_error("pointer is nullptr"); } } }; }