write a function template specialisation that tests if an argument is known at compile time

Paul Backus snarwin at gmail.com
Sat Aug 11 18:11:15 UTC 2018


On Saturday, 11 August 2018 at 05:17:51 UTC, Cecil Ward wrote:
> T myfunc(T)( T x, uint mask )
>    if ( mask == 3 )
>    {
>    return fast_func( x, mask );
>    }
>
> but of course this doesn't work because mask is not known at 
> compile-time. so I wondered if there is a way to do something 
> like static if ( isKnownAtCompileTime( mask ) ) but that would 
> not necessarily help me and probably isn't the right way.

You can create an overload where `mask` is passed as a template 
parameter:

T myfunc(uint mask, T)(T x)
{
     static if(mask == 3) {
         return fast_func(x, mask);
     } else {
         return func(x, mask);
     }
}

The same technique is used by `std.format.format` in the standard 
library to pass a format string that's known at compile time.


More information about the Digitalmars-d-learn mailing list