Overloads not returning appropriate info. [Field reflunkory]

Paul Backus snarwin at gmail.com
Sun Apr 7 14:53:09 UTC 2019


On 4/6/19 11:47 PM, Alex wrote:
> What you need to tell me is why using .stringof is bad. You have simply
> conjured up a rule and are stating it but not giving any reason why it
> is not a good idea to follow when, in fact, not following can be shown
> to be beneficial.

I'm not Adam, but I've also run into problems with .stringof, and have
found avoiding it to be a good idea in a lot of situations.

The problem with .stringof and string mixins is that types and symbols
carry information about their context with them--what module they're
from, what scope they're defined in, etc. This is why, for example, you
can pass a type defined in module a to a template defined in module b
and have it work without needed to add `import a` to module b.

When you convert a type or symbol to a string using .stringof, all of
this context information is stripped away. And in many cases, once that
information has been lost, it's impossible to recover. For example, if
all you have is the string "S", and two modules in your program define a
`struct S`, there's no way to know which one of those types your string
refers to.

If you say, "fine, I'll just use fully-qualified names," well, that
doesn't work either, because some types in D don't *have*
externally-visible names [1]. If you convert a type like that to a
string, you can never get the original type (with its context info)
back, no matter what you do.

All that said, it's perfectly fine to use .stringof for debugging and
custom error messages. But if you're using it to generate code, you are
almost certainly making a mistake.

[1] https://wiki.dlang.org/Voldemort_types


More information about the Digitalmars-d-learn mailing list