Here is some code:
#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]));
}
Unfortunately the first assert passes, and the second does not. I am not surprised by that result, but it would have been nice to be able to discern types that way.
My (sort of hackish) workaround:
#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());
}
This produces the desired result, but seems messy. Is there a better way to find out which type I am dealing with?