Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does std::is_polymorphic identify polymorphism?

I tried to understand the working of std::is_polymorphc in C++.
This is defined in type_traits.h:

template <class _Ty>
struct is_polymorphic : bool_constant<__is_polymorphic(_Ty)> {}; // determine whether _Ty is a polymorphic type

template <class _Ty>
_INLINE_VAR constexpr bool is_polymorphic_v = __is_polymorphic(_Ty);

I am not able to find the source code for __is_polymorphic.
Could someone help me understand how __is_polymorphic works ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

__is_polymorphic is a reserved keyword so it’s a compiler builtin i.e. it’s not implemented in library, it’s implemented directly into the compiler. So there is not source code to see, unless you look into the compiler source code.

On cppreference you can see a possible implementation:

namespace detail {
 
template <class T>
std::true_type detect_is_polymorphic(
    decltype(dynamic_cast<const volatile void*>(static_cast<T*>(nullptr)))
);
template <class T>
std::false_type detect_is_polymorphic(...);
 
} // namespace detail
 
template <class T>
struct is_polymorphic : decltype(detail::detect_is_polymorphic<T>(nullptr)) {};

This works by using the fact that dynamic_cast requires a polymorphic type to compile. detect_is_polymorphic is an overloaded function that uses SFINAE to check if dynamic_cast is valid on T.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading