digitalmars.D - typeid() woes
- Andrej Mitrovic (20/20) Aug 08 2010 test.d:
- Andrej Mitrovic (5/28) Aug 08 2010 I need to be a little patient. :) On the next page it explains the stati...
- bearophile (4/6) Aug 08 2010 Try typeof().
- Adam Ruppe (16/18) Aug 08 2010 Try this:
- Andrej Mitrovic (2/20) Aug 08 2010
test.d: class Contact { } class Friend : Contact { void reminder() { writeln("friend.reminder"); } } unittest { Contact c = new Friend; // c has type Contact but really refers to a Friend writeln(typeid(c)); c.reminder(); } This will not compile, as expected, since a Contact type doesn't have the reminder method. But if I comment out the c.reminder() line, writeln will return "test.Friend". Why is that?
Aug 08 2010
I need to be a little patient. :) On the next page it explains the static vs. dynamic type, so I guess typeid() always returns the dynamic type. I wonder if there's a way to get the static type, is there an equivalent function like typeid() for such a case? On Sun, Aug 8, 2010 at 11:57 PM, Andrej Mitrovic <andrej.mitrovich gmail.comwrote:test.d: class Contact { } class Friend : Contact { void reminder() { writeln("friend.reminder"); } } unittest { Contact c = new Friend; // c has type Contact but really refers to a Friend writeln(typeid(c)); c.reminder(); } This will not compile, as expected, since a Contact type doesn't have the reminder method. But if I comment out the c.reminder() line, writeln will return "test.Friend". Why is that?
Aug 08 2010
Andrej Mitrovic:I wonder if there's a way to get the static type, is there an equivalent function like typeid() for such a case?Try typeof(). Bye, bearophile
Aug 08 2010
On 8/8/10, Andrej Mitrovic <andrej.mitrovich gmail.com> wrote:I wonder if there's a way to get the static type, is there an equivalent function like typeid() for such a case?Try this: typeid(typeof( X )); typeof() returns the static type of the variable. Then, you can get the typeid of that returned static type. Here's a sample program: ==== import std.stdio; class Something { } class SomethingElse : Something {} void main() { Something o = new SomethingElse; writeln(typeid(typeof(o))); } ==== Prints: test6.Something
Aug 08 2010
Thanks, that works. On Mon, Aug 9, 2010 at 12:21 AM, Adam Ruppe <destructionator gmail.com>wrote:On 8/8/10, Andrej Mitrovic <andrej.mitrovich gmail.com> wrote:I wonder if there's a way to get the static type, is there an equivalent function like typeid() for such a case?Try this: typeid(typeof( X )); typeof() returns the static type of the variable. Then, you can get the typeid of that returned static type. Here's a sample program: ==== import std.stdio; class Something { } class SomethingElse : Something {} void main() { Something o = new SomethingElse; writeln(typeid(typeof(o))); } ==== Prints: test6.Something
Aug 08 2010