Skip to content

Instantly share code, notes, and snippets.

@syusui-s
Created March 15, 2014 04:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syusui-s/9561875 to your computer and use it in GitHub Desktop.
Save syusui-s/9561875 to your computer and use it in GitHub Desktop.
C++ の instance_of
// 参考: http://simple-asta.blogspot.jp/2013/06/c-instanceof.html
#include <iostream>
class Object {
public:
template<typename T>
inline bool instance_of()
{
return dynamic_cast<const T*>(this) != 0;
}
virtual ~Object(){}
};
class Derived_One : public Object {
};
class Derived_Two : public Object {
};
int main() {
Object *obj[2];
obj[0] = new Derived_One();
obj[1] = new Derived_Two();
for (int i = 0; i < 2; ++i)
{
std::cout << "obj[" << i << "] is ";
if (obj[i]->instance_of<Derived_One>()) {
std::cout << "Derived_One!";
} else if (obj[i]->instance_of<Derived_Two>()) {
std::cout << "Derived_Two!";
} else {
throw "Unrecognized Object";
}
std::cout << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment