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 ?
>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.