Thread overview
Distinguish recursive Templates
May 22, 2015
Manfred Nowak
May 22, 2015
Matt Kline
May 22, 2015
Manfred Nowak
May 22, 2015
Timon Gehr
May 22, 2015
Manfred Nowak
May 22, 2015
How can one determine the recursion depth for templated types?

Example code:

import std.stdio;
class Set(T){
  override string toString(){
    return "Set";
  }
}
void main(){
  auto s0= new Set!uint;
  writeln( s0); // writes Set

  auto s1= new Set!(Set!uint);
  writeln( s1); // should write SetSet
}
May 22, 2015
On Friday, 22 May 2015 at 21:13:50 UTC, Manfred Nowak wrote:
> How can one determine the recursion depth for templated types?
>
> Example code:
>
> import std.stdio;
> class Set(T){
>   override string toString(){
>     return "Set";
>   }
> }
> void main(){
>   auto s0= new Set!uint;
>   writeln( s0); // writes Set
>
>   auto s1= new Set!(Set!uint);
>   writeln( s1); // should write SetSet
> }

Why should the last line write SetSet? (It doesn't.) toString isn't making any use of the template argument T, so no recursion occurs.
May 22, 2015
Matt Kline wrote:

> isn't making any use of the template argument T

Correct. I do not know how to use `T' to determine the recursion depth of the template---and I want no further parameter.

-manfred
May 22, 2015
On 05/23/2015 12:12 AM, Manfred Nowak wrote:
> Matt Kline wrote:
>
>> isn't making any use of the template argument T
>
> Correct. I do not know how to use `T' to determine the recursion depth of
> the template---and I want no further parameter.
>
> -manfred
>

import std.stdio, std.range, std.algorithm;

template getDepth(T){
    static if(is(T==Set!S,S)) enum getDepth=1+getDepth!S;
    else enum getDepth=0;
}
class Set(T){
    override string toString(){
        enum r="Set".repeat.take(getDepth!Set).join;
        return r;
    }
}
void main(){
    auto s0=new Set!uint;
    writeln(s0); // writes Set
    auto s1=new Set!(Set!uint);
    writeln(s1); // writes SetSet
}

May 22, 2015
Timon Gehr wrote:

> template getDepth(T){
>      static if(is(T==Set!S,S)) enum getDepth=1+getDepth!S;
>      else enum getDepth=0;
> }

Thx. Seems that I have to relearn a lot.

-manfred