Lazy template arguments?

monarch_dodra monarchdodra at gmail.com
Sun Jan 13 03:26:56 PST 2013


On Sunday, 13 January 2013 at 11:15:03 UTC, comco wrote:
> On Saturday, 5 January 2013 at 10:37:31 UTC, bearophile wrote:
>> In some case I'd like a hypothetical static ternary operator 
>> usable on types:
>>
>> alias T = (U.sizeof <= 16) ?? ushort : size_t;
>>
>> That is equivalent to:
>>
>> static if (U.sizeof <= 16) {
>>    alias T = ushort;
>> } else {
>>    alias T = size_t;
>> }
>>
>>
>> The syntax of a possible library implementation is acceptable:
>>
>> alias T = Ternary!(U.sizeof <= 16, ushort, size_t);
>>
>>
>> But I think to implement it well in library code you need a 
>> kind of "lazy" for types (it means the T2 type is not computed 
>> if b is false):
>>
>>
>> template Ternary(bool b, T1, lazy T2) {
>>    static if (b)
>>        alias Ternary = T1;
>>    else
>>        alias Ternary = T2;
>> }
>>
>>
>> Are such lazy type arguments generally useful for other 
>> purposes?
>>
>> Bye,
>> bearophile
>
> Isn't the whole ct metaprogramming with types kind of 
> functional and immutable? So there is no perceivable difference 
> between the results using different evaluation strategies? I 
> thought that the template instantiation is already implemented 
> as being lazy?

It's lazy in terms of instantiation, not in terms of evaluation 
of args. For example, if you write:

//----
lias T = Ternary!(U.sizeof <= 16, Foo!A, Foo!B);
//----

Then the compiler *will* instantiate Foo!B.

Bearophile: Is this proposal a pure optimization trick, or is 
there some functionality gains here. The only one I can think of, 
is if "Foo!B" would fail to compile. Is this what you are going 
for...?

Also:
//----
template Ternary(bool b, T1, lazy T2) {
//----
While is only T2 lazy?


More information about the Digitalmars-d-learn mailing list