以下是一些代码:
#include <typeinfo>
#include <assert.h>
#include <vector>
class Super {};
class Sub1 : public Super {};
class Sub2 : public Super {};
int main() {
std::vector<Super*> vec;
vec.push_back(new Sub1);
vec.push_back(new Sub2);
assert(typeid(vec[0]) == typeid(vec[1]));
assert(typeid(vec[0]) != typeid(vec[1]));
}
不幸的是,第一个断言通过,而第二个没有通过。我对这个结果并不感到惊讶,但能够以这种方式辨别类型会很好。
我的(有点hackish)解决方法:
#include <typeinfo>
#include <assert.h>
#include <vector>
enum SubTypeEnum {
Sub1_T,
Sub2_T
};
class Super {
SubTypeEnum _type;
public:
Super(SubTypeEnum __type) : _type(__type) {}
SubTypeEnum type() { return _type; }
};
class Sub1 : public Super {
public:
Sub1() : Super(Sub1_T) {}
};
class Sub2 : public Super {
public:
Sub2() : Super(Sub2_T) {}
};
int main() {
std::vector<Super*> vec;
vec.push_back(new Sub1);
vec.push_back(new Sub2);
assert(vec[0]->type() != vec[1]->type());
assert(vec[0]->type() == vec[1]->type());
}
这会产生所需的结果,但看起来很混乱。有没有更好的方法来找出我正在处理的类型?
答案 0 :(得分:1)
首先你稍微错误地使用typeinfo
,当应用于指针它返回指针的类型时,但是当应用于解除引用的指针时,它返回指向的对象的实际类型,只要基类型至少有一个虚函数(通常它是析构函数)。所以以下内容将起作用:
class Super {
public:
virtual ~Super() {}
};
class Sub1 : public Super {};
class Sub2 : public Super {};
int main() {
std::vector<Super*> vec;
vec.push_back(new Sub1);
vec.push_back(new Sub2);
assert(typeid(vec[0]) == typeid(vec[1]));
assert(typeid(*vec[0]) != typeid(*vec[1]));
}
其次,做这种类型的转换通常被认为是你做错事的标志。例如,而不是
void foo(Base* v) {
//Here SOMETHING and SOMETHING_ELSE are constants we calculate elsewhere.
if( typeid(*v)==SOMETHING ) { cout<<"Got a SOMETHING"<<endl; }
else if (typeid(*v)==SOMETHING_ELSE ) { cout<<"Got a SOMETHING ELSE"<<endl; }
}
或大致相当的
void foo(Base* v) {
if( dynamic_cast<Something*>(v) ) { cout<<"Got a SOMETHING"<<:endl; }
else if ( dynamic_cast<SomethingElse*>(v) { cout<<"Got a SOMETHING ESLE"<<endl; }
通常会将功能添加到基类中:
class Base
{
public:
virtual void printMessage()=0;
};
class Something : public Base
{
void printMessage() { cout<<"Got a SOMETHING"<<endl; }
}
class SomethingElse : public Base
{
void printMessage() { cout<<"Got a SOMETHING ELSE"<<endl; }
}
void foo(Base * v)
{
v->printMessage();
}