This article presents a pair of macros for implementing
R.T.T.I.
(Run-Time Type Information) in
the C++ language. The naming of these macros is inspired by Java.
It should be noted that there is another R.T.T.I. system in C++ namely
<typeinfo.h>. This system is an alternative to that system but
my system doesn't work properly with multiple inheritance.
1.0 R.T.T.I. Macros
The following macros add R.T.T.I. functionality to C++
classes:
With the above macro definitions in place, classes can have R.T.T.I.
functionality by calling these macros in their class definitions.
Example:
classA {
public:
RTTI_SAME(A);
RTTI_ROOT(B1);
RTTI_ROOT(B2);
RTTI_ROOT(C);
public:
// rest of class definition
};
classB1 : publicA {
public:
RTTI_SAME(B1);
voidb1_method() {
cout << "(inside b1_method)\n";
}
public:
// rest of class definition
};
classB2 : publicA {
public:
RTTI_SAME(B2);
voidb2_method() {
cout << "(inside b2_method)\n";
}
public:
// rest of class definition
};
classC : publicB1 {
public:
RTTI_SAME(C);
voidc_method() {
cout << "(inside c_method)\n";
}
public:
// rest of class definition
};
3.0 Using R.T.T.I.
With the above class definitions in place, R.T.T.I. can be achieved by the
following statements.'
voidfoo(A* a)
{
if (a->instanceof_A()) {
cout << "(a is instance of A)\n";
}
if (a->instanceof_B1()) {
cout << "(a is instance of B1)\n";
B1* b = a->castto_B1();
b->b1_method();
}
if (a->instanceof_B2()) {
cout << "(a is instance of B2)\n";
B2* b = a->castto_B2();
b->b2_method();
}
if (a->instanceof_C()) {
cout << "(a is instance of C)\n";
C* c = a->castto_C();
c->c_method();
}
}
intmain()
{
A* a = newA();
A* b1 = newB1();
A* b2 = newB2();
A* c = newC();
foo(a); // outputs:
// (a is instance of A)
cout << endl;
foo(b1); // outputs:
// (a is instance of A)
// (a is instance of B1)
// (inside b1_method)
cout << endl;
foo(b2); // outputs:
// (a is instance of A)
// (a is instance of B2)
// (inside b2_method)
cout << endl;
foo(c); // outputs:
// (a is instance of A)
// (a is instance of B1)
// (inside b1_method)
// (a is instance of C)
// (inside c_method)
}
4.0 Emacs Syntax Highlighting
Here is some Emacs Lisp code that highlights the R.T.T.I. methods in the
keyword face. Place the following code in your .emacs file:
;; The following code highlights the R.T.T.I. methods:
(add-hook 'font-lock-mode-hook 'my-cc--rtti)
(defunmy-cc--rtti ()
(if (eq major-mode 'c++-mode)
(font-lock-add-keywords nil
'(("\\<\\(instanceof_\\|castto_\\)\\(\\sw*\\)"
(1 font-lock-keyword-face t)
(2 font-lock-type-face t)))
'APPEND)))