如何在编译时检查类型是否为polymorhic
How to check at compile time if type is polymorhic
我有模板函数。在template函数中,我对template参数使用dynamic_cast。但是,由于不能在非多态类型上使用dynamic_cast,我想在编译时检查类型是否是多态的(至少有一个虚拟函数),如果类型不是多态的,我将跳过使用dynamic_cast。这可能吗?
您可以使用std::is_polymorphic
:
struct Foo {};
std::cout << std::is_polymorphic<Foo>::value << std::endl;
您可以将其与std::enable_if
结合使用,根据其值使用不同的代码。
与@juancopanza 相比的另一种方式
template<class T>
struct IsPolymorphic
{
struct Derived : T {
virtual ~Derived();
};
enum { value = sizeof(Derived)==sizeof(T) };
};
class PolyBase {
public:
virtual ~PolyBase(){}
};
class NPolyBase {
public:
~NPolyBase(){}
};
void ff()
{
std::cout << IsPolymorphic<PolyBase >::value << std::endl;
std::cout << IsPolymorphic<NPolyBase>::value << std::endl;
}
相关文章:
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 检查函数返回类型是否与STL容器类型值相同
- 检查某些类型是否是模板类 std::optional 的实例化
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 检查一个类型是否直接派生自"enable if"上下文中的另一个类型(是其子类型)
- 如何检查模板类型是否可以从给定类型构造
- 用于检测函数类型是否为否的特征
- 了解类型是否可调用
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 键入特征以检查类型是否可从流和 MSVC 读取
- 从双精度转换为整数的显式类型是否始终检查整数溢出?
- 如何获取类型是否真正可移动可构造
- 在编译时检查类型是否为 std::basic_string<T> C++
- 在C++中,转换为simd类型是否有未定义的行为
- POD类型是否完全等同于琐碎的标准布局类型
- 聚合类型是否意味着它也是标准布局
- 有没有一种方法可以使用SFINAE来检测一个类型是否实现了给定的抽象基类
- 验证(使用 static_assert)元组类型是否遵循某种顺序(有状态编译时检查)
- 强制转换为不相关的引用类型是否违反严格的别名规则?
- 特征:从数组类型中获取标量类型是否记录?