Created
March 15, 2014 04:32
-
-
Save syusui-s/9561875 to your computer and use it in GitHub Desktop.
C++ の instance_of
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 参考: 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