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

Cecil Ward d at cecilward.com
Sun Aug 12 02:27:02 UTC 2018


On Sunday, 12 August 2018 at 02:17:21 UTC, Cecil Ward wrote:
> On Sunday, 12 August 2018 at 00:55:50 UTC, Paul Backus wrote:
>> On Sunday, 12 August 2018 at 00:15:37 UTC, Cecil Ward wrote:
>>> Paul, what would the calls look like?
>>>
>>> I am about to misunderstand things completely so here goes :-)
>>>
>>> It would be a bit kludgy having to switch from one calling 
>>> syntax to another, putting the mask argument in the template 
>>> parameters or in the normal position. Or have I 
>>> misunderstood? And if the caller did not use the right call 
>>> syntax variant then the optimisation would not happen. Thing 
>>> is, as it is the details are nicely hidden and the caller 
>>> does not even need to thing about the fact that an 
>>> (eponymous) template is being used.
>>
>> As far as I know, there's no way to *guarantee* the 
>> optimization and keep the normal function call syntax. 
>> Probably the best you can do is write the mask check as a 
>> regular if statement, put `pragma(inline, true)` in the 
>> function, and hope the optimizer is smart enough to get rid of 
>> the branch.
>
> I was thinking about reflection and powerful things like 
> traits. Would a test to see if a static if compile do the trick 
> ? You ask the question using traits : "does the following 
> compile? : { static if ( mask == 3 ) { }; }"  - any use?

I am out of my depth but I am also wondering about using mixin in 
some way, conditionally.

And the kind of thing I am also thinking about is something like

    if this ( xxx ) compiles then xxx // put in the code under a 
conditional compilation if
    else pull in alternative code

and all the ifs are compile time. so zero run time penalty which 
absolutely essential in my case because in fact the bodies are 
just single instructions and it is a choice between a cheaper 
instruction ( or no instruction at all ) and a 3-4 times more 
costly instruction, but an if statement is 50 times more 
expensive because of branch misprediction risk as well as the 
cost of the test itself



More information about the Digitalmars-d-learn mailing list