The following seems to work:
#include<typeinfo>
#include<iostream>
class B { virtual void foo() {} };
class D1 : public B { };
class D2 : public B { };
class D3 : public B { };
template<typename T1, typename T2>
bool is_same(const T1& t1, const T2& t2) {
return typeid(t1) == typeid(t2);
}
bool is_same_no_template(const B& b1, const B& b2) {
return typeid(b1) == typeid(b2);
}
int main(){
D1 d1;
D2 d2;
D1 d1b;
B b;
std::cout<<std::boolalpha
<<"d1 == d2 ? "<<is_same(d1, d2)<<std::endl
<<"d1 == d1b ? "<<is_same(d1, d1b)<<std::endl
<<"d1 == b ? "<<is_same(d1, b)<<std::endl;
std::cout<<"No Template"<<std::endl;
std::cout<<std::boolalpha
<<"d1 == d2 ? "<<is_same_no_template(d1, d2)<<std::endl
<<"d1 == d1b ? "<<is_same_no_template(d1, d1b)<<std::endl
<<"d1 == b ? "<<is_same_no_template(d1, b)<<std::endl;
return 0;
}
Compiling with gcc 4.7.2 I get the following output:
[Prompt] g++ example.cpp -std=c++11
[Prompt] ./a.out
d1 == d2 ? false
d1 == d1b ? true
d1 == b ? false
No Template
d1 == d2 ? false
d1 == d1b ? true
d1 == b ? false
Beware that this code will not compile if you decide to compile without "run-time type information" (RTTI; the -fno-rtti
compile flag in gcc).