How to specify a template that uses unqualified type, like any normal function

Dominikus Dittes Scherkl via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 14 15:14:21 PDT 2017


On Monday, 14 August 2017 at 17:43:44 UTC, Dominikus Dittes 
Scherkl wrote:
> On Monday, 14 August 2017 at 15:20:28 UTC, Steven Schveighoffer 
> wrote:
>> What you can do, is:
>>
>> auto foo(T)(T n) if (is(T == Unqual!T))
>> {
>>    // normal implementation
>> }
>>
>> auto foo(T)(T n) if (!is(T == Unqual!T) && 
>> isImplicitlyConvertible!(T, Unqual!T))
>> {
>>    return foo!(Unqual!T)(n);
>> }
>
> Ok, I'll try that out.

Yeah, works fine. I've improved this to

T foo(T)(T n)
{
    static if(!is(Unqual!T == T)) return foo!(Unqual!T)(n);
    else
    {
        // normal implementation
    }
}

So it's basically 2 lines of overhead. That's acceptable. The 
check for isImplicitlyConvertible is not necessary, because if 
it's not it will error out anyway.

As this in fact leads to some decrease in code size (as the 
instances for const or shared parameters are now much smaller or 
in fact completely removed by the inliner, much less template 
code duplication happens), I will add this to a lot of templates 
- seems this will become some sort of standard D boilerplate code.

Thanks for the help!


More information about the Digitalmars-d-learn mailing list