4 ms·
Strictly speaking I think the term for what's requested would be reflection - but I don't think these terms are especially precise ones. The sorts of things I'
by to3m 9y ago
Strictly speaking I think the term for what's requested would be reflection - but I don't think these terms are especially precise ones.
The sorts of things I've used reflection for:
- logging - getting the name of things' types, turning enums into strings, etc.
- generating debugging UI - for every bool field in your object, you get a check box; for every enum field, a combo box; for every string field, a text box; and so on
- serialization/deserialization - it has limitations, but you can get surprisingly far before you run into them, and for many situations it doesn't matter
- scripting language integration - for every type of interest in your program, find its fields and methods, and link those up to the scripting system
- dependency injection - given a set of known services, when creating an object (perhaps by name, provided at runtime, which you match to a type by scanning the list of types available) provide it with the services it needs (determined by, say, examining the types of the parameters of its constructor). Typically you'd cross-reference types of parameter with types of each service to match them up, but there are various options
Especially good with a C#-like metadata system that lets you assign user-defined properties to fields that your calling code can query to get further info. For example, you might not want to serialize certain fields, or you might want to hide some fields from the UI, and so on.
(If this doesn't convince you, fine; for my money, though, this is the #1 missing feature from C++. But, like the post's author, my background is working on video games... maybe this is just stuff that only video games people would want?)
- colanderman 9y agoenum→string I agree 100% is useful for debugging. string→enum, and enum→string for production purposes I find questionable, since they couple your implementation internals to an externally-visible protocol, of which a change in one should not necessitate a change in the other. Of course relying on an implicit mapping speeds initial development… but I'm the one who has to maintain those things ;)