我试图理解 C++ 中的工作原理std::is_polymorphc。这是定义在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);
Run Code Online (Sandbox Code Playgroud)
我无法找到 的源代码__is_polymorphic。有人可以帮助我了解如何__is_polymorphic工作吗?
bol*_*lov 10
__is_polymorphic是一个保留关键字,因此它是内置于编译器中的,即它不在库中实现,而是直接在编译器中实现。所以,没有源代码可看,除非你看编译器的源代码。
在cppreference上,您可以看到可能的实现:
Run Code Online (Sandbox Code Playgroud)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)) {};
这是通过使用需要多态类型才能编译的事实dynamic_cast来实现的。detect_is_polymorphic是一个重载函数,它使用 SFINAE 检查dynamic_cast在 上是否有效T。
| 归档时间: |
|
| 查看次数: |
373 次 |
| 最近记录: |