Skip to main content
gamedev.net
🔒 Locked

reading unknown types

Started by Lode Feb 26, 2008 at 2:16 AM 1 replies 400+ views
Original Post
Lode
Lode
Hi, Say you have a class A which has children B, C, D, E, F, etc... You have a whole list of A*'s that can be of any of the child-types, and want to write the list to XML. You implement class A butthe children are implemented by someone else elsewhere so you can't know what they'll be and how they'll need to be written to XML. The above is easily done: so you make it go through the list of A*'s, and call avirtual XML-writing function so that the B, C, D, etc... will write themselves correctly (with a parameter for the pretty indentation in XML and such but that doesn't matter here). So it's really nice that you can save that way from one central point to XML tags for any type of object that you don't have to know about. But: how could it be implemented to read it again? Of course what's written also needs to be read. From your central point you only know about A, but if you encounter a tag for B, C, D, ... you'll have to construct one of the correct type which you can't. How can the reading of the above structure be done from a central point but without you having to know about the child-types, but somehow the child-types themselves creating themselves in your list? In C++ btw.
Lode
Lode
I found a possible solution: Have custom modules that implement those child classes, register themselves to the main framework that implements A. A will ask the registered modules if they recognise the tag, if not, move on to the next one and so on.
Zipster
Zipster
You're on the right track, but there are a few problems I can see with that approach. What if two child classes "recognize" the same tag? Only the first one that recognizes the tag gets a chance to instantiate and will most likely fail if it wasn't the same class that wrote the data. But even if you allow multiple classes to instantiate and only keep the one that succeeded, there's a chance more than one class can succeed if they all read/write the same data, even though they're all completely different internally. Enforcing unique tags during registration isn't safe either, because it's likely the tags will only be the same from run to run if the exact same classes register each time, in the same order.

Ultimately it comes down to each class having a unique ID that remains constant from run to run. Some sort of RTTI might be necessary, although admittedly I've always known all the types at compile-time when I've had to solve this problem in the past.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.