Returning const? -- A potential solution

Daniel Keep daniel.keep.lists at gmail.com
Sat Mar 7 22:15:59 PST 2009



Jason House wrote:
> Daniel Keep wrote:
>> Perhaps it would be worth adding this:
>>
>> "Compilers may optionally, as a quality of implementation feature,
>> generate an overload of the function which specifically handles
>> immutable arguments.  This should only be done for optimised builds.
>> Any user code which disallows this optimisation may be reported as a
>> warning."
>>
>> Considering that one of the reasons for having transitive immutability
>> is to aid in optimisation, it seems a shame to toss it overboard with a
>> pair of lead shoes.
> 
> That's an important point that should be addressed after the basic solution 
> is found.

Why?  If the solution is designed without thought to this, you could end
up in a situation where it's no longer possible.

I'm not saying this has to be done from the get-go; I'm saying it should
be kept in mind so we don't lock ourselves out from it.

>>>   * Functions can be virtual
>> Well, they can be virtual now: you just have to manually instantiate the
>> function 3 times.
> 
> I was thinking of the contrast to template-based solutions that avoid code 
> duplication, but cause both code bloat and are not virtual.  (Virtual 
> template functions is a whole thread in itself that I hope to avoid at the 
> moment)

You can define a templated function, then mix it in with three different
type arguments.  Yes, there's two functions in there which probably have
the same implementation, but they're still virtual.

As for virtual templates, that's impossible unless the D runtime grows a
compiler.

>> One would hope the following would work:
>>
>> static if( isConst!(typeof(a)) )
>> {
>>     // Slow, safe way
>> }
>> else
>> {
>>     // Exploit mutability
>> }
> 
> In such scenarios, people are not complaining about code duplication and 
> will just code an overloaded function...  I hope that can stay out of this 
> thread since it's really a different problem.

What if it's a one-line difference in a 20-line function?

And it's very related to this: you either allow the above construct or
you don't.

Let's say the compiler takes the method, generates the single
implementation, and off it goes.

How does it parse the above construct?  You've got to define THAT either
way.

  -- Daniel



More information about the Digitalmars-d mailing list