写了一个模板:
template<class T1, class T2>
bool IsDerivedFrom()
{
T1 *t1 = new T1;
if (T2 *pt2 = dynamic_cast<T2 *>(t1)) //编译出错指向这一行
return true;
else
return false;
}
调用如下:
cout << IsDerivedFrom<Derived, Base2>() << endl;
编译的时候就出现错误:error C2683: “dynamic_cast”:“Derived”不是多态类型
template<class T1, class T2>
bool IsDerivedFrom()
{
T1 *t1 = new T1;
if (T2 *pt2 = dynamic_cast<T2 *>(t1)) //编译出错指向这一行
return true;
else
return false;
}
调用如下:
cout << IsDerivedFrom<Derived, Base2>() << endl;
编译的时候就出现错误:error C2683: “dynamic_cast”:“Derived”不是多态类型
解决方案
20
这样判断吧;
template<typename T , typename TBase> class TIsDerived
{
public:
static int t(TBase* base)
{
return 1;
}
static char t(void* t2)
{
return 0;
}
enum
{
Result = ( sizeof(int) == sizeof(t( (T*)NULL) ) ),
};
};
bool isDeriveFrom = TIsDerived<ClassA, ClassB>::Result;
template<typename T , typename TBase> class TIsDerived
{
public:
static int t(TBase* base)
{
return 1;
}
static char t(void* t2)
{
return 0;
}
enum
{
Result = ( sizeof(int) == sizeof(t( (T*)NULL) ) ),
};
};
bool isDeriveFrom = TIsDerived<ClassA, ClassB>::Result;
10
可以直接用 std::is_base_of
非要本人实现的话,看看
boost::is_base_of
非要本人实现的话,看看
boost::is_base_of