Overload using nogc

Sativa via Digitalmars-d digitalmars-d at puremagic.com
Sun Nov 23 12:07:36 PST 2014


On Saturday, 22 November 2014 at 16:56:58 UTC, Ary Borenszweig 
wrote:
> On 11/21/14, 12:36 AM, Jonathan Marler wrote:
>> Has the idea of function overloading via nogc been explored?
>>
>> void func() @nogc
>> {
>>     // logic that does not use GC
>> }
>> void func()
>> {
>>     // logic that uses GC
>> }
>> void main(string[] args) // @nogc
>> {
>>     // if main is @nogc, then the @nogc version of func
>>     // will be called, otherwise, the GC version will be
>>     func();
>> }
>>
>> This could be useful for the standard library to expose 
>> different
>> implementations based on whether or not the application is 
>> using the GC.
>
> If you have a version that doesn't use the GC, what's the 
> reason to prefer one that uses it?

because, say, you can have two versions! Is that not good enough 
for you?

e.g., you can later on write a nogc version and simply switch 
between the two implementations by toggling the attribute on main.

Benefits? Easy:

1. It allows you to update your library to handle nogc 
progressively
2. It allows you to more easily debug your code. If it works with 
@gc and not @nogc then obviously it's in the @nogc code.
3. It reduces code bloat and confusion because one doesn't have 
to have multiple names of the same function floating around. 
e.g., allocate_gc, allocate_nogc_heap, etc.

The problem here is that such a rule chooses one or the other 
which reduces its usefulness. If one could simply request nogc 
functions, say, then

void main() @request(@nogc(heap))
{
     allocate();
     other_overload();
}

could attempt to use all @nogc overloads, in this case, the above 
expands to essentially

void main() @request(@nogc(heap))
{
     allocate_nogc_heap(); //
     other_overload_gc();   // assuming it exists, if not, it will 
use whatever overloads exist that
}

But with all this added complexity I don't think one gets a huge 
benefit in this case. Simply making the compiler GC agnostic and 
by using allocators, I think one gets basically the same 
functionality with more clarity.

It may work in other cases though. Essentially the concept is to 
extend overloading to work with attributes.

e.g.,

void func(...)
void func(...) @attr1
void func(...) @attr2

are all overloads with the attributes also being overloaded.

func at random(...)

calls a random overload(chosen at compile time).

func at request(@attr1)(...)

attempts to call func with @attr1 but falls back on the 
non-overloaded ones, etc.

func at attr1(...) calls the function with @attr1 or fails if it 
doesn't exist.

Ultimately, having such a metadata system helps partition similar 
functions in a program and then do something more complex.

Not sure if it would actually be that useful since we can 
effectively already do this type of stuff, albeit with more work 
and confusion.







More information about the Digitalmars-d mailing list