Typed variadic template syntax?

inout inout at gmail.com
Wed Jan 29 14:25:43 PST 2014


On Wednesday, 29 January 2014 at 07:02:00 UTC, Andrei 
Alexandrescu wrote:
> On 1/28/14 4:14 PM, bearophile wrote:
>> This is not an enhancement request, but it presents a potential
>> enhancement.
>>
>>
>> This is C++11 code:
>>
>> template<int... digits> struct value;
>>
>> template<> struct value<> {
>>     static const int v = 0;
>> };
>>
>> template<int first, int... rest> struct value<first, rest...> {
>>     static int const v = 10 * value<rest...>::v + first;
>> };
>>
>>
>>
>> You can translate it to D like this:
>>
>>
>> enum isInt(T) = is(T == int);
>>
>> template value(xs...) if (allSatisfy!(isInt, xs)) {
>>     static if (xs.length == 0)
>>         enum value = 0;
>>     else
>>         enum value = xs[0] + 10 * value!(xs[1 .. $]);
>> }
>
> int value(int xs[]...) {
>   int result = 0;
>   foreach (i; xs) {
> 	result += 10 * result + i;
>   }
>   return result;
> }
>
> unittest
> {
>   static assert(value(1, 2) == 21);
> }
>
>
> Andrei

This allocates memory and as such an inferior solution. I'd 
prefer ugly code over this any day.


More information about the Digitalmars-d mailing list