Accessing template parameters from outside?
Norbert Nemec
Norbert at Nemec-online.de
Mon Apr 24 13:32:05 PDT 2006
As far as I can see, an IsExpression allows to check whether T is an
exact type, but is there a possibilty to check whether T is an instance
of a certain template with arbitrary parameter? Like:
is(T:mytemplate!(???))
Even more: once I know that T is an instance of mytemplate, is there a
way to find out what the template parameters are?
Basically, what would be needed is some pattern matching mechanism like:
if(is(T:mytemplate($N)))
where the IsExpression is true if the pattern fits, and at the same
time, the "wildcard" $N is assigned to whatever it matches.
The whole thing is inspired by the template mechanism of C++ which
allows the following:
--------------------
template<int N> class vector {
double data[N];
}
template<typename T> class container {
T content;
void dump() {
cout << "Container for unknown type\n";
}
}
// simple specialization
template<> class container<double> {
double content;
void dump() {
cout << "Container for double\n";
}
}
// specialization for template as parameter:
template<int N> class container<vector<N> > {
vector<N> content;
void dump() {
cout << "Container for vector of size " << N << "\n";
}
}
container<int> icontainer;
icontainer.dump();
// prints: "Container for unknown type"
container<double > dcontainer;
dcontainer.dump();
// prints: "Container for double"
container<vector<3> > vcontainer;
vcontainer.dump();
// prints: "Container for vector of size 3"
---------------------
Meaning: inside the specialized template, I can, at compile time,
analyse the parameters.
The corresponding code in D would like something like:
---------------------
class vector(int N) {
double[N] data;
};
class container(T) {
T content;
void dump() {
static if(is(T:double)) {
printf("Container for double\n");
} else static if(is(T:vector ?????)
printf("Container for vector %i\n",?????);
} else {
printf("Container for unknown type\n");
}
}
};
---------------------
How should I write the lines containing the "?????"? I know the example
above it stupid, but the core point itself came up when I tried several
solutions in for the units library yesterday. I found ugly workarounds,
but no real solution.
More information about the Digitalmars-d
mailing list