Overloading based on attributes - is it a good idea?

Jonathan Marler johnnymarler at gmail.com
Tue May 28 19:49:40 UTC 2019


On Tuesday, 28 May 2019 at 18:07:47 UTC, Walter Bright wrote:
> On 5/28/2019 10:35 AM, Jonathan Marler wrote:
>> After reading Walter's response here, another thought came to 
>> mind that instead of attribute overloading, a template with 
>> static-if could also be used.
>
> @nogc attributes are often inferred. Such constructs would make 
> it undecidable.

You're right it's undecidable inside the function, but I think 
it's decidable if you check it at the call site. So if we could 
pass that information to the template then we could use it.  
Using a default template parameter could work, though, we'd 
likely need to modify __traits(compiles) to work in the callers 
context when used as a default template parameter, or create a 
new trait like __trait(compilesAtCallSite):


int main(string[] args)
{
     nogcExample();
     gcExample();
     return 0;
}

version (WorksToday)
{
     void nogcExample() @nogc
     {
         allocateString!(__traits(compiles, new Object))(100);
     }
     void gcExample()
     {
         allocateString!(__traits(compiles, new Object))(100);
     }
     auto allocateString(bool allowGC)(size_t size)
     {
         static if (allowGC)
         {
             return new char[size];
         }
         else
         {
             import core.stdc.stdlib : malloc;
             return (cast(char*)malloc(size))[0 .. size];
         }
     }
}
else version (UseCompilesAtCallSite)
{
     void nogcExample() @nogc
     {
         allocateString(100);
     }
     void gcExample()
     {
         allocateString(100);
     }
     auto allocateString(bool allowGC = 
__traits(compilesAtCallSite, new Object))(size_t size)
     {
         static if (allowGC)
         {
             return new char[size];
         }
         else
         {
             import core.stdc.stdlib : malloc;
             return (cast(char*)malloc(size))[0 .. size];
         }
     }
}

Then again maybe if the nogcExample/gcExample functions were also 
templates, then we wouldn't be able to infer whether or not gc 
was available...not sure on that one.



More information about the Digitalmars-d mailing list