Let\'s say I have some base abstract class and three different classes that derive and implement its methods. Is there is a \'Type\' object like as in C#? Or in other words, how
You can create instanceof
like methods that can detect the type of an object using templates and std::is_base_of (1) or dynamic_cast only for polymorphic objects (2).
1 Live sample
template inline bool instanceof(const T) {
return is_base_of ::value;
}
int main() {
Module1 module;
if(instanceof(module)) {
cout << "Module1" << endl;
}
if(instanceof(module)) {
cout << "Module2" << endl;
}
if(instanceof(module)) {
cout << "ModuleBase" << endl;
}
}
2 Live sample
class ModuleBase { public: virtual ~ModuleBase(){} };
template inline bool instanceof(const ModuleBase * base) {
return dynamic_cast(base);
}
int main() {
Module1* module = new Module1();
if(instanceof(module)) {
cout << "Module1" << endl;
}
if(instanceof(module)) {
cout << "Module2" << endl;
}
if(instanceof(module)) {
cout << "ModuleBase" << endl;
}
}
The object is both of type ModuleBase
and Module1
. I think with that you can achieve what you need with these.