一个例子中更容易解释,
class base {
//....
}
class derived1 : public base {
//...
}
在我的库中,有一个基类指针。库的用户必须创建从 base 或 derived1 派生的类,并分配指向该类的指针。
如何检查用户定义的类是从哪个类派生的?
我对提议的编译时 x 运行时解决方案有一些评论。除了评估时间外,is_base_of
和dynamic_cast
有不同的要求,它们的答案可能不同。
1(首先(如其他人所指出的(要使用dynamic_cast
,基类和派生类必须是多态的(必须至少有一个virtual
方法(。 is_base_of
不要求类型是多态的。
(2(is_base_of
的操作数都是类型,而dynamic_cast
需要一个类型(< >
内(和一个对象(( )
内(。
(3(dynamic_cast
和is_base_of
可以根据继承的类型(public
与protected
或private
(给出不同的答案(或者一个可以编译而另一个不能(。例如,考虑:
struct B { virtual ~B() {} }; // polymorphic, so it can be used in a dynamic_cast
struct D1 : public B {}; // polymorphic by (public) inheritance
struct D2 : private B {}; // polymorphic by (private) inheritance
D1 d1;
D2 d2;
我们有
static_assert(std::is_base_of<B, D1>::value, "");
static_assert(std::is_base_of<B, D2>::value, "");
assert(dynamic_cast<B*>(&d1));
assert(!dynamic_cast<B*>(&d2)); // Notice the negation.
实际上,最后一行在GCC(error: 'B' is an inaccessible base of 'D2'
(中产生了编译器错误。VS2010确实编译了它(只产生类似于GCC错误消息的警告(。
(4(可以通过异常处理技巧放宽对类多态的要求。考虑:
struct B { }; // not polymorphic
struct D1 : public B {}; // not polymorphic
struct D2 : private B {}; // not polymorphic
D1 d1;
D2 d2;
template <typename B, typename D>
const B* is_unambiguous_public_base_of(const D* obj) {
try {
throw obj;
}
catch (const B* pb) {
return pb;
}
catch (...) {
}
return nullptr;
}
然后我们有
static_assert(std::is_base_of<B, D1>::value, "");
static_assert(std::is_base_of<B, D2>::value, "");
assert((is_unambiguous_public_base_of<B>(&d1)));
assert(!(is_unambiguous_public_base_of<B>(&d2))); // Notice the negation.
值得一提的是,is_unambiguous_public_base_of
比 dynamic_cast
慢得多,并且(在下面更新中提到的重命名后变得更加明显(总是返回一个 nullptr
对于向下投射:
B* b1 = &d1;
assert(dynamic_cast<D1*>(b1)); // Requires D1 and B to be polymorphic.
assert(!(is_unambiguous_public_base_of<D1>(b1))); // Notice the negation.
有关此技巧的过时参考可在以下链接中找到:
第1 部分、第 2 部分和代码
免责声明:上述is_unambiguous_public_base_of
的实施只是为了说明观点而提出的草案,并没有正确处理const
和volatile
资格。
更新:在这篇文章的先前版本中,is_unambiguous_public_base_of
被命名为my_dynamic_cast
,这是一个混乱的根源。所以我把它改成一个更有意义的名字。(感谢Jan Herrmann。
使用dynamic_cast。
if (dynamic_cast<DerivedClass*>(ptr)) {
std::cout << "Class is derived from DerivedClass.";
}
检查类是否派生自特定类(编译时(
您可以使用std::is_base_of
:
#include <type_traits>
....
const bool isBase = std::is_base_of<base, TheOtherClass>::value;
如果TheOtherClass
派生自base
,则isBase
为真。
我认为这个问题的答案非常困难。当然有std::is_base_of
和dynamic_cast
.两者都为您提供了一些非常有限的信息。第三个选项是函数重载。使用所有这些技术,您可以在代码中选择应执行的特殊路径。
std::is_base_of
可以在布尔上下文中解释,它派生自std::true_type
或std::false_type
。这一事实使得可以将其用作函数的参数,并通过函数重载使用编译时多态性。第一个示例演示如何在布尔上下文中使用它,但你没有任何进一步的特定类型信息。因此,在大多数情况下编译都会失败(有关进一步的说明,请参阅此处(:
template<class T>
void do_it1(T const& t) {
if (std::is_base_of<T,derived1>::value) {
// we have a derived1
} else {
// we have a base
}
}
第二个版本是简单的函数重载。这里使用编译时多态性,但所有运行时类型信息都会丢失(使用虚函数和dynamic_cast
除外(:
void do_it2(Base const& b) {
// we have a base your algorithm for base here
}
void do_it2(Derived2 const& d) {
// Derived algorithm here
}
现在第三个版本结合了两者:
template<class T>
void do_it3_impl(T const& t, std::true_type) {
// here t will be of a type derived from derived1
}
template<class T>
void do_it3_impl(T const& t,std::false_type) {
// here t will be of type not derived from derived1
}
template<class T>
void do_it_3(T const& t) {
do_it3_impl(t, std::is_base_of<T,derived1>()); // here we forward to our impl
}
第三种变体通常用于不使用运行时 poylmorphism 的仅标头库(搜索 std::advance
以获取 example(。
现在到运行时多态性。这里有dynaminc_cast
变体:
void do_it4(Base const* ptr)
if (derived1 const* obj = dynamic_cast<derived*>(ptr)) {
// here we have obj with type derived1*
} else {
// here we have only base
}
如果此变体不够快,您可以将 onw 强制转换为 derived1:
class derived1;
class base {
// as above
public:
virtual derived1 const* to_derived1() const {
return 0;
}
};
class derived1
: public base
{
// ...
virtual derived1 const* to_derived1() const {
return this;
}
};
void do_it5(Base const* ptr)
if (derived1 const* obj = ptr->to_derived1() {
// here we have obj with type derived1*
} else {
// here we have only base
}
这很快,但它只能很好地扩展为极少数(大约 1(派生类。
最后但并非最不重要的一点是,您应该考虑您的类设计,并考虑在base
、derived1
或其他类中实现哪些方法。您应该明确寻找策略模式。
您可以通过多种方式执行此操作。正如其他人指出的那样,最常见的是dynamic_cast<>和std::is_base_of。后者在编译时使用,而dynamic_cast<>
可以在运行时使用。但是,dynamic_cast<>
仅在源类是多态的(即至少有一个虚函数 - 它可以是方法或其析构函数(时才有效。否则,编译器将触发错误。
如果库函数采用指向基类的指针,编译器将仅接受指向派生自基类的类的指针。我的答案是用经典的方法类型安全来处理它。根据我的经验,这种类型检查就足够了。拥有25年的行业经验,我质疑是否需要进行此检查。也许这样的基本问题不受欢迎?我希望看到有必要进行这种向上投射的理由。我永远不必那样做。相反,即我经常需要向下投掷。