Question

I'm very bad with recursion, never used it before. I know the theory of it .. not that that helps :)) For my problem i have a structure of TCollection that contains TCollection and TCollectionItem etc .. I have to write a recursion function that will read all my TCollectionItems. Here is graphical view:

TCollection->TCollectionItem(s)->TCollection->TCollectionItem(s)

TCollection can have 1 or even 2,3 TCollection's under him OR none.

Here are few more examples:

TCollection->TCollectionItem

TCollection->TCollectionItem->TCollection->TCollectionItem->TCollection->TCollectionItem

etc ..

Please tell me if i described the problem badly, i probably did .. please ask if something is unclear :)

Thanks for the support!

Was it helpful?

Solution

You haven't indicated the prototypes of the TCollection methods so as to enumerate and to read your TCollectionItems, and other needed details.

However, this is definitely solved by: The Composite Design Pattern.

The aim of this pattern is to traverse a recursive form, and to forward a call on a composite onto its composants and so on, until that reaches the leaves ( TCollectionItems with an empty TCollection in your case)

OTHER TIPS

The only way to recursively access child TCollection objects, without knowing the class types of the owning TCollectionItem objects so you can type-cast them, is to use the VCL's RTTI information.

In C++Builder versions prior to XE, VCL-based RTTI is only available for __published properties. Given a TCollectionItem (or any general TObject) object pointer, you can use the GetPropList() function declared in TypInfo.hpp to retreive a list of that object's published property information. You can then loop through that list, checking for any properties that report a TypeKind value of tkClass. When you find one, use the GetObjectProp() function to retreive that property's TObject pointer value, and then use dynamic_cast to make sure it is really a TCollection object before you access its child TCollectionItem objects.

In C++Builder 2010, a new Enhanced RTTI system was introduced, declared in Rtti.hpp, that provides information for all members of a class, including non-published properties and fields. With this enhanded RTTI, a child TCollection does not need to be declared as a __published property anymore. Under this system, you would use the TRttiContext class to access a TRttiType object for your recursion's starting TCollectionItem object, then use the TRttiType::GetFields() and TRttiType::GetProperties() methods to look for child TRttiField and TRttiProperty items that report a TypeKind of tkClass, then use the TRttiField::GetValue() and TRttiProperty::GetValue() methods to get the TObject object pointer that can be type-casted to a TCollection pointer with dynamic_cast.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top