如何实现编译时检查,一个downcast在一个CRTP是有效的? [英] How to implement a compile-time check that a downcast is valid in a CRTP?
问题描述
我有一个普通的旧CRPT(请不要因为访问限制而分心 - 问题不在于他们):
I have a plain old CRPT (please don't get distracted by access restrictions - the question is not about them):
template<class Derived>
class Base {
void MethodToOverride()
{
// generic stuff here
}
void ProblematicMethod()
{
static_cast<Derived*>(this)->MethodToOverride();
}
};
如下:
class ConcreteDerived : public Base<ConcreteDerived> {
void MethodToOverride()
{
//custom stuff here, then maybe
Base::MethodToOverride();
}
};
现在 static_cast
我需要一个向下转换(不是向上转换),所以我必须使用显式转换。在所有合理的情况下,转换将是有效的,因为当前对象确实是派生类。
Now that static_cast
bothers me. I need a downcast (not an upcast), so I have to use an explicit cast. In all reasonable cases the cast will be valid since the current object is indeed of the derived class.
但是如果我改变层次结构而转换现在变得无效了怎么办?
But what if I somehow change the hierarchy and the cast now becomes invalid?
我可以在某种程度上执行编译时检查,在这种情况下显式的downcast是有效的吗?
May I somehow enforce a compile-time check that an explicit downcast is valid in this case?
推荐答案
在编译期,你只能检查静态类型,这是 static_cast
已经做了。
At compile-time you can only check the static types, and that's what static_cast
already does.
给定一个 Base *
,它只是,并且只能在运行时知道其动态类型,也就是说,它是否实际指向 ConcreteDerived
或其他东西。所以如果你想检查这个,它必须在运行时完成(例如使用 dynamic_cast
)
Given a Base*
, it is only, and can only be, known at run-time what its dynamic type is, that is, whether it actually points to a ConcreteDerived
or something else. So if you want to check this, it has to be done at runtime (for example by using dynamic_cast
)
这篇关于如何实现编译时检查,一个downcast在一个CRTP是有效的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!