typeid可以获得一个对象的动态类型名称

#include<iostream>
#include<vector>
#include<typeinfo>
using namespace std;

class Base{
public:
virtual ~Base(){}
};

class Derived:public Base{
public:
~Derived(){}
};

int main()
{
vector<Base*> v;
for(int i=0;i<100;i++){
v.push_back(new Base);
v.push_back(new Derived);
}
for(vector<Base*>::const_iterator iter = v.begin();
iter != v.end();
++iter)
{
if(Derived* d = dynamic_cast<Derived*>(*iter)){
cout << typeid(d).name() << endl;
}else{
cout << typeid(*iter).name() << endl;
}
}
}

P4Base
P7Derived
P4Base
P7Derived
...



#include<iostream>
#include<typeinfo>
#include<string>
using namespace std;

template<typename T>
void print(const T& t)
{
cout << "typeid:" << typeid(t).name() << endl;
}

int main()
{
int a = 0;
float b = 1;
double c = 2;
string d = "3";
print(a);
print(b);
print(c);
print(d);
}

typeid:i
typeid:f
typeid:d
typeid:Ss


type_info::before来sort

#include<stdlib.h>
#include<vector>
#include<iostream>
#include<typeinfo>
#include<map>

using namespace std;

class Shape{
public:
virtual void draw() = 0;
virtual ~Shape(){};
virtual int edge(){return 3;}
};

class Circle:public Shape{
public:
void draw(){cout << "Circle::draw()"<<endl; }
int edge(){return 3;}
~Circle(){cout << "~Circle()" << endl; }
};

class Rectangle : public Shape{
public:
void draw(){ cout << "Rectangle::draw()" << endl;}
int edge(){return 4;}
~Rectangle(){cout << "~Rectangle()" << endl;}
};

class Square : public Shape{
public:
void draw(){ cout << "Square::draw()" << endl;}
int edge(){return 4;}
~Square(){ cout << "~Square()" << endl;}
};

void drawQuad(Shape& shape){
if(shape.edge()<4){
cout << "not a polygone" << endl;
}else{
cout << "a polygone" << endl;
}
}

struct TInfoLess{
bool operator()(const type_info* t1,const type_info* t2)const{
return t1->before(*t2);
}
};

typedef map<const type_info*,vector<Shape*>,TInfoLess> shapeMap;

int main(){
srand(time(0));//seed a random
vector<Shape*> v;
shapeMap smap;
int num = 0;
Shape *shape;
for(int i=0;i<10;++i){
num = rand();
switch(num%3){
case 0:
shape = new Circle;
break;
case 1:
shape = new Rectangle;
break;
case 2:
shape = new Square;
break;
}
smap[&typeid(*shape)].push_back(shape);
}
for(shapeMap::iterator iter = smap.begin();iter!=smap.end();++iter){
//print
}
}