std::is_polymorphic_C++中文网

template< class T >
struct is_polymorphic;

(C++11 起)

T多态类(即声明或继承至少一个虚函数的非联合类),则提供等于 true 的成员常量 value 。对于任何其他类型, valuefalse

T 是非联合类类型,则 T 应为完整类型;否则行为未定义。

添加 is_polymorphic is_polymorphic_v (C++17 起) 的特化的程序行为未定义。

模板形参

辅助变量模板

template< class T >
inline constexpr bool is_polymorphic_v = is_polymorphic<T>::value;

(C++17 起)

继承自 std::integral_constant

成员常量

T多态类类型则为 true ,否则为 false
(公开静态成员常量)

成员函数

转换对象为 bool ,返回 value
(公开成员函数)
返回 value
(公开成员函数)

成员类型

可能的实现

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)) {};

示例

#include <iostream>
#include <type_traits>
 
struct A {
    int m;
};
 
struct B {
    virtual void foo();
};
 
struct C : B {};
 
int main()
{
    std::cout << std::boolalpha;
    std::cout << std::is_polymorphic<A>::value << '\n';
    std::cout << std::is_polymorphic<B>::value << '\n';
    std::cout << std::is_polymorphic<C>::value << '\n';
}

输出:

参阅