Get struct template types

ed growlercab at gmail.com
Tue Feb 4 01:58:52 PST 2014


On Tuesday, 4 February 2014 at 09:46:01 UTC, evilrat wrote:
> On Tuesday, 4 February 2014 at 09:39:48 UTC, evilrat wrote:
>> On Tuesday, 4 February 2014 at 09:30:22 UTC, ed wrote:
>>> Hi,
>>>
>>> given a struct like so:
>>>
>>> struct S(alias N, T) {...}
>>>
>>> is there a way to get the template parameters of S? Something 
>>> like:
>>>
>>> S.typetuple[0] == N,
>>> S.typetuple[1] == T
>>>
>>> I've had a look at std.typecons and std.typetuple but I don't 
>>> see what I'm missing something and cannot see a way to do the 
>>> above.
>>>
>>> Thanks,
>>> ed
>>
>> typeof(N).stringof will return type of N as string
>> for details read http://dlang.org/expression.html
>
> oops sorry, it's for another people.
>
> what are you trying to achieve? when passing types as template 
> args it is still types, so again typeof should give you type 
> for variables(in such cases there is typeof), otherwise type is 
> type. also, afaik it is not possible to store types in tuple, 
> but i think you can store variables in tuple and retrieve their 
> types at runtime


I am trying to set up an isS, isSOfN or isSOfT so I can create 
functions that allow restricted types of S based on all, or only 
one of the template parameters.

Like so (pseudo-D code)
---
struct S(alias N, T) {}

//
// Hopefully it is clear what I am trying to do here
enum isSOfN = template(alias N,STYPE) {
     static assert(N == STYPET.typetuple[0]);
}

enum isSOfT = template(T,STYPE) {
     static assert(T == STYPET.typetuple[1]);
}
//


void f(T)(T t) if(isSOfN!(3, T)) { // allow S with N=3 and any T 
(see below)
}

...
...

auto s3i = S!(3,int);
auto s3f = S!(3,float);

s3i.f(); // Succeeds
s3f.f(); // Succeeds

auto S4i = S!(4,int);
s4i.f(); // compile time error
--

I'm looking into T.stringof now, I might be able to get it 
working with some compile-time string magic of D :)

If this is a bad way to go about it please let me know. I'm 
trying to learn idiomatic D as I go.

Thanks,
ed


More information about the Digitalmars-d-learn mailing list