typeid 也可以应用于模板类。模板类生成对象的类型部分取决于在实例化时我们为模板类的类型参数指定的数据类型。因此,如果模板类使用不同类型的数据来创建两个对象,那么生成的两个对象将是不同的类型。
测试程序1:
[C++] 纯文本查看 复制代码 #include "stdafx.h"
#include <iostream>
using namespace std;
template <class T> class myclass {
T a;
public:
myclass(T i) { a = i; }
};
int _tmain(int argc, _TCHAR* argv[])
{
myclass<int> ob1(10), ob2(9);
myclass<double> ob3(7.2);
cout << "Type of ob1 is ";
cout << typeid(ob1).name() << endl;
cout << "Type of ob2 is ";
cout << typeid(ob2).name() << endl;
cout << "Type of ob3 is ";
cout << typeid(ob3).name() << endl;
if (typeid(ob1) == typeid(ob2))
cout << "ob1 and ob2 are the same type\\n";
if (typeid(ob3) == typeid(ob1))
cout << "Error\\n";
else
cout << "ob1 and ob2 are different types.\\n";
return 0;
}
运行输出:Type of ob1 is class myclass<int>
Type of ob2 is class myclass<int>
Type of ob3 is class myclass<double>
ob1 and ob2 are the same type
ob1 and ob2 are different types. 有输出可见,即使由同一模板创建的两个对象,如果由于参数类型不同,那么这两个对象也不同。
测试程序2:
[C++] 纯文本查看 复制代码 #include "stdafx.h"
#include <iostream>
#include <cstdlib>
using namespace std;
//figure 是一个模板类
template <class T> class figure {
protected:
T x, y;
public:
figure(T i, T j) {
x = i;
y = j;
}
virtual T area() = 0;
};
template <class T> class triangle : public figure<T> {
public:
triangle(T i, T j) : figure<T>(i, j) {}
T area() {
return x * 0.5 * y;
}
};
template <class T> class rectangle : public figure<T> {
public:
rectangle(T i, T j) : figure<T>(i, j) { }
T area() {
return x * y;
}
};
template <class T> class circle : public figure<T> {
public:
circle(T i, T j=0) : figure<T>(i, j) { }
T area() {
return 3.14 * x * x;
}
};
//创建从类 figure 派生的类的对象
figure<double> *generator()
{
switch( rand() % 3 ) {
case 0:
return new circle<double>(10.0);
case 1:
return new triangle<double>(10.1, 5.3);
case 2:
return new rectangle<double>(4.3, 5.7);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
int main()
{
figure<double> *p;
int i;
int t = 0, c = 0, r = 0;
//生成并统计对象
for (i = 0; i < 10; i++) {
p = generator();
cout << "Object is " << typeid(*p).name(); //运行时类型识别
cout << ". ";
//统计对象
if( typeid(*p) == typeid(triangle<double>)) t++;
if( typeid(*p) == typeid(rectangle<double>)) r++;
if( typeid(*p) == typeid(circle<double>)) c++;
cout << "Area is " << p->area() << endl;
}
cout << endl;
cout << "Objects generated:\\n";
cout << " Triangles: " << t << endl;
cout << " Rectangles: " << r << endl;
cout << " Circles: " << c << endl;
return 0;
}
运行输出:Object is class rectangle<double>. Area is 24.51
Object is class rectangle<double>. Area is 24.51
Object is class triangle<double>. Area is 26.765
Object is class triangle<double>. Area is 26.765
Object is class rectangle<double>. Area is 24.51
Object is class triangle<double>. Area is 26.765
Object is class circle<double>. Area is 314
Object is class circle<double>. Area is 314
Object is class triangle<double>. Area is 26.765
Object is class rectangle<double>. Area is 24.51
Objects generated:
Triangles: 4
Rectangles: 4
Circles: 2 |