[Insight-developers] Depth of nested templates

Brad King brad.king@kitware.com
Wed, 14 Mar 2001 15:23:55 -0500 (EST)


> As Brad told me, I have this too deep nested template problem in my code:
> [.....]

Just so that everyone is clear on what I mean by nested template depth,
here is an example:

// Recursive type definition.
template <int Depth>
struct MyStruct
{
  typedef typename MyStruct<Depth-1>::Type Type;
};

// End the recursion at zero.
template <>
struct MyStruct<0>
{
  typedef int Type;
};

Now, to determine the type of "MyStruct<10>::Type", the compiler has to
instantiate "MyStruct<10>", "MyStruct<9>", ..., "MyStruct<1>" in order to
get to "MyStruct<0>::Type".  This is a depth of 10 template
instantiations.  Compilers like GCC have a limit to the depth they will
allow.  By default it is 17 for GCC.  The reason a limit is necessary is
so that the compiler doesn't get into an infinity loop of instantiations
by, say, trying to find the type "MyStruct<-1>::Type".

On GCC, the limit can be increased with the "-f-template-depth-N" flag,
where N is the depth limit.  MSVC doesn't seem to have a limit, and just
crashes.  If you want, cut and paste the code at the bottom of this
message into a new file in Visual Studio's editor, and watch what happens.
Make sure everything is saved first :)

What Yinpeng has encountered is code that naturally reaches the 17
instantiation limit.  It gives an error on GCC unless you specify
something like -f-template-depth-50 (I didn't actually find the exact
number needed).  We could consider requiring this flag to build Insight,
but if there are other, just as clean implementations, then they should be
used instead.  Deep template instantiation depths are slow to build
anyway.  Thoughts, anyone?

-Brad

--------------------------
template <int Depth>
struct MyStruct
{
  typedef typename MyStruct<Depth-1>::Type Type;
};

MyStruct<10>::Type x;