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 ?
CodePudding user response:
__is_polymorphic
is a reserved keyword, so it's built-in to the compiler i.e. it's not implemented in library, it's implemented directly in the compiler. So, there is no source code to see, unless you look at the compiler's 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 in order to compile. detect_is_polymorphic
is an overloaded function that uses SFINAE to check if dynamic_cast
is valid on T
.
CodePudding user response:
With magic. I know, it's unsatisfying, but that's the answer. Most of type_traits
is compiler-level magic. The C compiler knows that when it sees something like is_polymorphic
, it should look through the list of methods available to the argument class (which is not something you can do as a C programmer, it's something only the compiler can do) and does the check via an ad-hoc method.