所以一般都有
class A { ... };
class B { ... };
class C: public A, public B {}; // C inherits from A and B.
当我们创建一个C实例并希望将它传递给某个函数时,我们是否检查传递给函数的类是否正在扩展A?
答案 0 :(得分:9)
C
被定义为继承自A
,因此无需检查:
C
的实例也必须是A
(以及B
)。
但是,如果您有一个以A
为参数的函数,则可以使用dynamic_cast<>
检查实例是否实际为C
:
void function(const A& a)
{
const C* c = dynamic_cast<const C*>(&a);
if (c)
{
// a is an instance of C and you can use c to call methods of C
} else
{
// a is not an instance of C.
}
}
但要使其工作,基类类型必须是多态(它必须至少有一个虚方法)。
答案 1 :(得分:3)
您需要执行此操作的唯一时间是在编译期间,因为隐式转换在其他任何地方都有效。但是如果你想看看某个类型T是否是某种类型S的基础,那么你可以使用SFINAE(或者只使用is_base_of&lt;&gt;):
template < typename T, typename S >
struct is_base_of // checks if T is a base of S
{
typedef char (yes&) [1];
typedef char (no&) [2];
void yes check(T*);
void no check(...);
enum { value = sizeof(check(static_cast<S*>(0))) == sizeof(yes); }
};