IS THERE an IS keyword in C++ like in C#?
YES, there is an IS keyword in C++. Just like in C#.
A few days ago I had this question and I saw this answer “NO” and I took it and accepted it.
Only today I saw in some sample code just use of typeid(). And guess what? typeid() turns BLUE in the IDE!
#include <iostream>
#include <string>
using namespace std;
class Entity
{
public:
int hp ;
};
class Grunt : public Entity
{
public:
string name ;
};
int main()
{
Grunt grom ;
grom.hp = 500 ;
grom.name = "GROM HELLSCREAM!" ;
const type_info * typeOfG = &typeid( grom ) ;
cout << typeOfG->name() << endl;
Entity wisp ;
wisp.hp = 120 ;
const type_info * typeOfWisp = &typeid( wisp ) ;
cout << typeOfWisp->name() << endl;
// equivalent of C# is:
//if( grom is Grunt )
//{
//}
// accomplished by
string classGrunt = "class Grunt" ;
if( typeid(grom).name() == classGrunt )
{
cout << "Grom is a grunt" << endl;
}
else
{
cout << "Grom is NOT a grunt" << endl;
}
// so we coudl make this a bit more elegant by
#define is( obj, type ) typeid(obj).name()==type
if( is( grom, classGrunt ) )
{
cout << "Grom is a grunt" << endl;
}
else
{
cout << "Grom is NOT a grunt" << endl;
}
/*
class type_info {
bool operator==( type_info rhs ) ;
bool operator!=( type_info rhs ) ;
int before( type_info rhs ) ;
const char* name();
const char* raw_name();
} ;
*/
}
2 Trackbacks/Pingbacks
[...] Bobobobo’s Weblog technology and the internets About MECG 1CG 2INDEXbrowse « THERE IS A C# IS keyword equivalent in C++ [...]
[...] in a row.. which I believed. One was the C# keyword IS equivalent in C++ doesn’t exist (which it does) and the other was there is no equivalent of keyword base in c++ (which there [...]