Accessing template parameters from outside?

Oskar Linde oskar.lindeREM at OVEgmail.com
Tue Apr 25 00:05:38 PDT 2006


Norbert Nemec skrev:
> 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)))
> 
[snip]
> 
> 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.

The shortest fix to do the above I can think of is:

   } else static if(is(typeof(content.data))) {
     printf("Container for vector %i\n",content.data.length);

Another way is:

class vector(int N) {
   const vector_N = N;
   double[N] data;
}

...

   } else static if(is(typeof(T.vector_N))) {
     printf("Container for vector %i\n",T.vector_N);


But I guess those are what you call ugly workarounds. I don't think 
there is any nice general way to get the arguments of an instantiated 
template. But you can if you make sure all your templates have alias and 
const parameters corresponding to the template parameters. I guess you 
could even check the .mangleof property of the type at compile time to 
make sure it is an instantiation of a certain template. (You could even 
get the template parameters from the mangled name...)

More often, I think one would have more use of checking that a certain 
type has certain properties rather than specializing for a specific 
template. I.e:

// A queue is something that has push_back and pop_front methods.
template IsQueue(T) {
	static if (is(typeof(T.push_back)) && is(typeof(T.pop_front)))
		const bool IsQueue = true;
	else
		const bool ISQueue = false;
}

(This could of course be made much better)

/Oskar



More information about the Digitalmars-d mailing list