Reuse of variables referencing const objects

Chris Nicholson-Sauls ibisbasenji at gmail.com
Mon Mar 9 20:00:50 PDT 2009


Sergey Kovrov wrote:
> On 3/9/2009 8:50 PM, Chris Nicholson-Sauls wrote:
>> While not strictly intuitive, you could do this:
>> auto var = Rebindable!(const Foo)(new Foo);
>> assert(var.opDot !is null);
>>
>> As 'opDot' returns the wrapped object (with const intact). The downside
>> to that, however, is that it won't work in those cases where
>> Rebindable's template parameter was mutable, as then it simply aliases
>> it. This shouldn't be a problem in general use, though. Only in generic
>> code, which could try to check for Rebindable.
> 
> Thanks Chris, this approach indeed works, its a shame I haven't figured 
> this on my own.
> 
> I wonder if it's proper usage of opDot.. In general, is it safe for 
> client code to rely on implementation of opDot and call it directly?

Technically, no, not really.  Then again, it isn't absolutely horrible 
either.  It would be better if there were some other means of testing 
for null, which could be overwritten.  The only alternative that comes 
immediately to mind would be an opCast to T, but then it would supersede 
any opCast defined on T.  (Then again, in code dealing with Rebindable 
one could always chain the casts: 'cast(Bar)cast(Foo)var'.  Ugly, but 
possibly effective.

> And in this particular case we rely on the fact that Rebindable uses 
> opDot to forward calls.

Considering its the only way of doing so in a completely generic manner 
anyhow, I don't think its a big deal.  It could become annoying, 
however, for generic code.

> Slightly off-topic... In Python world (and I guess any other dynamic 
> language) it is not valid to make assumptions based on implementation. 
> Only safe way to use "foreign code" (a library, framework) is to follow 
> documentation. That way authors of libraries are free to change their 
> code as long as it comply with documented behavior.
> 
> 
> -- serg.

The sentiment applies in almost any language, but a static typed 
language does allow for a few more assumptions.  I have a habit of 
crawling through the sources of libraries I use anyhow, so I'm sure I 
occasionally do things in "*evil*" undocumented ways.  ;)

Maybe there should be an 'IsNull' template that understands 
Rebindable's.  That said, I'm not sure what kind of is() invocation 
would match a struct template...  (pssst, template ninjas...)


-- Chris Nicholson-Sauls


More information about the Digitalmars-d-learn mailing list