Recursive template expansion
Norbert Nemec
Norbert at Nemec-online.de
Mon Mar 1 01:16:41 PST 2010
Hi there,
trying out a few ideas on expression templates, I stumbled over the
following problem, for which I cannot find a solution. The code below
demonstrates what I try to do:
I need to construct a nested template type at compile time. Any
expression should correspond to an equivalent nested tree of templates
which can then be unraveled at compile time.
For some reason, the D compiler complains about a "recursive template
expansion" as soon as I use ((a+b)+c). My guess is that this is supposed
to protect against infinite recursions at compile time. In this case,
however, there is actually no risk of that. Nested types are only needed
at the depth of nested expressions that actually occur.
Is there any fundamental error in my thinking? Some simple
misunderstanding? Some slightly different syntax to be used? Or is it
simply an unnessessary restriction in the compiler that could easily be
removed?
Apart from all that, I want to point out that the error message does not
even give a line number in the code. If any such error occurs within a
larger piece of software, identifying the problem would be a nightmare!
Greetings,
Norbert
---------------
import std.stdio;
struct sum(A,B) {
A a;
B b;
auto opAdd(T)(T a) { return .sum!(sum,T)(this,a); }
}
struct base {
auto opAdd(T)(T a) { return .sum!(base,T)(this,a); }
}
void main() {
base a,b,c;
// first a few working examples
writeln(typeid(a)); // base
writeln(typeid(a+b)); // sum!(base,base).sum
writeln(typeid(a+(b+c))); // sum!(base,sum!(base,base)).sum
sum!(sum!(base,base),base) d;
writeln(typeid(d)); // sum!(sum!(base,base),base).sum
// the following produces
// Error: recursive template expansion for
// template argument sum!(base,base)
writeln(typeid((a+b)+c)); // sum!(sum!(base,base),base).sum
}
---------------
More information about the Digitalmars-d
mailing list