"else if" for template constraints

Idan Arye via Digitalmars-d digitalmars-d at puremagic.com
Mon Aug 17 15:32:08 PDT 2015


On Monday, 17 August 2015 at 21:27:47 UTC, Meta wrote:
> On Monday, 17 August 2015 at 17:17:15 UTC, Steven Schveighoffer 
> wrote:
>> On 8/17/15 1:00 PM, Idan Arye wrote:
>>
>>> It looks a bit ugly, that the `else` is after a function 
>>> declaration
>>> instead of directly after the if's "then" clause. How about 
>>> doing it
>>> with the full template style?
>>>
>>>      template replaceInPlace(T, Range)
>>>      if(isDynamicArray!Range &&
>>>          is(Unqual!(ElementEncodingType!Range) == T) &&
>>>          !is(T == const T) &&
>>>          !is(T == immutable T))
>>>      {
>>>          void replaceInPlace(ref T[] array, size_t from, 
>>> size_t to,
>>> Range stuff)
>>>          { /* version 1 that tries to write into the array 
>>> directly */ }
>>>      }
>>>      else if(is(typeof(replace(array, from, to, stuff))))
>>>      {
>>>          void replaceInPlace(ref T[] array, size_t from, 
>>> size_t to,
>>> Range stuff)
>>>          { /* version 2, which simply forwards to replace */ }
>>>      }
>>
>> Yes, I like this much better.
>>
>> -Steve
>
> At that point, couldn't you just use static if inside the body 
> of the template instead of using template constraints?

No. Consider this: http://dpaste.dzfl.pl/a014aeba6e68. The having 
two foo templates is illegal(though it'll only show when you try 
to instantiate foo), because each of them covers all options for 
T. When T is neither int nor float, the foo *function* in the 
first template is not defined, but the *foo* template is still 
there.

With the suggested syntax, the first foo template would only be 
defined for int and float, and the second will only be defined 
for char and bool - so there is no conflict.


More information about the Digitalmars-d mailing list