www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Extracting template parameters

reply Joseph Rushton Wakeling <joseph.wakeling webdrake.net> writes:
Suppose that I have two struct templates which take identical parameter lists:

     struct Foo(T1, T2, T3)
     {
         ...
     }

     struct Bar(T1, T2, T3)
     {
         ...
     }

Now suppose that I have a Foo which has been instantiated with a given set of 
parameters.  Is there any way for me to say, "now instantiate a Bar with the 
same parameters?"

The use-case I'm thinking of is a function something like this (somewhat 
pseudo-code-y):

     auto fooToBar(FooInstance f)
     {
         Bar!(f.T1, f.T2, f.T3) b;
         // set values etc.
         return b;
     }

Of course the f.T1 notation is my fiction, but it gives the idea of what is 
needed -- is there a means to extract and use template parameters in this way? 
I assume something from std.traits but it's not entirely clear what or how ...
Nov 06 2012
parent reply "Dan" <dbdavidson yahoo.com> writes:
On Tuesday, 6 November 2012 at 15:20:43 UTC, Joseph Rushton 
Wakeling wrote:

 Of course the f.T1 notation is my fiction, but it gives the 
 idea of what is needed -- is there a means to extract and use 
 template parameters in this way? I assume something from 
 std.traits but it's not entirely clear what or how ...
Would something like this be what you are after? import std.stdio; struct Foo(_T1, _T2, _T3) { alias _T1 T1; alias _T2 T2; alias _T2 T3; } struct Bar(_T1, _T2, _T3) { alias _T1 T1; alias _T2 T2; alias _T2 T3; } auto fooToBar(F)(F f) { Bar!(F.T1, F.T2, F.T3) b; writeln("I have a ", typeid(typeof(b))); return b; } void main() { alias Foo!(int, string, char) X; X x; fooToBar(x); } Thanks Dan
Nov 06 2012
parent Joseph Rushton Wakeling <joseph.wakeling webdrake.net> writes:
On 11/06/2012 04:34 PM, Dan wrote:
 Would something like this be what you are after?
Yes! I actually had tested something similar, but as I was using the variable name when trying to extract the parameter, it didn't work. Thanks very much!
Nov 06 2012