Explorar o código

meta: meta_type::can_cast (see #1028)

skypjack %!s(int64=2) %!d(string=hai) anos
pai
achega
eaa93d287e
Modificáronse 2 ficheiros con 17 adicións e 0 borrados
  1. 9 0
      src/entt/meta/meta.hpp
  2. 8 0
      test/entt/meta/meta_type.cpp

+ 9 - 0
src/entt/meta/meta.hpp

@@ -1324,6 +1324,15 @@ public:
         return index < template_arity() ? meta_type{*ctx, node.templ.arg(internal::meta_context::from(*ctx), index)} : meta_type{};
         return index < template_arity() ? meta_type{*ctx, node.templ.arg(internal::meta_context::from(*ctx), index)} : meta_type{};
     }
     }
 
 
+    /**
+     * @brief Checks if a type supports direct casting to another type.
+     * @return True if direct casting is allowed, false otherwise.
+     */
+    [[nodiscard]] bool can_cast(const meta_type &other) const noexcept {
+        // casting this is UB in all cases but we aren't going to use the resulting pointer, so...
+        return internal::try_cast(internal::meta_context::from(*ctx), node, other.node, this);
+    }
+
     /**
     /**
      * @brief Returns a range to visit registered top-level base meta types.
      * @brief Returns a range to visit registered top-level base meta types.
      * @return An iterable range to visit registered top-level base meta types.
      * @return An iterable range to visit registered top-level base meta types.

+ 8 - 0
test/entt/meta/meta_type.cpp

@@ -303,6 +303,14 @@ TEST_F(MetaType, TemplateInfo) {
     ASSERT_EQ(entt::resolve<std::shared_ptr<int>>().template_arg(1u), entt::meta_type{});
     ASSERT_EQ(entt::resolve<std::shared_ptr<int>>().template_arg(1u), entt::meta_type{});
 }
 }
 
 
+TEST_F(MetaType, CanCast) {
+    auto type = entt::resolve<derived_t>();
+
+    ASSERT_FALSE(type.can_cast(entt::resolve<void>()));
+    ASSERT_TRUE(type.can_cast(entt::resolve<base_t>()));
+    ASSERT_TRUE(type.can_cast(entt::resolve<derived_t>()));
+}
+
 TEST_F(MetaType, Base) {
 TEST_F(MetaType, Base) {
     auto type = entt::resolve<derived_t>();
     auto type = entt::resolve<derived_t>();