How to use typeid with template class in C++

2 Answers

0 votes
#include <iostream>

using std::cout;
using std::endl;

template <class T> class AClass {
	T val;
public:
	AClass(T _val) { val = _val; }
};

int main()
{
	AClass<int> o1(99);
	AClass<double> o2(3.4);

	cout << "Type of o1: " << typeid(o1).name() << endl;
	cout << "Type of o2: " << typeid(o2).name() << endl;

	return 0;
}

/*
run:

Type of o1: class AClass<int>
Type of o2: class AClass<double>

*/

 



answered Jun 6, 2018 by avibootz
0 votes
#include <iostream>

using std::cout;
using std::endl;

template <class T> 
class CClass {
	T n;
public:
	CClass(T _n) {
		n = _n;
	}
};

int main()
{
	CClass<int> o1(13), o2(435);
	CClass<double> o3(3.14);

	cout << typeid(o1).name() << endl;
	cout << typeid(o2).name() << endl;
	cout << typeid(o3).name() << endl;

	if (typeid(o1) == typeid(o2))
		cout << "o1 type == o2 type" << endl;
	if (typeid(o2) == typeid(o3))
		cout << "o2 type == o3 type" << endl;
	else
		cout << "o2 type != o3 type" << endl;
	return 0;
}



/*
run:

class CClass<int>
class CClass<int>
class CClass<double>
o1 type == o2 type
o2 type != o3 type

*/

 



answered Aug 2, 2018 by avibootz

Related questions

1 answer 136 views
1 answer 225 views
1 answer 220 views
1 answer 202 views
1 answer 159 views
159 views asked Dec 10, 2020 by avibootz
1 answer 215 views
1 answer 187 views
...