define new types within templates

grauzone none at example.net
Tue Dec 29 16:13:43 PST 2009


teo wrote:
> There was a way to define new types within templates and I think that I 
> have seen that demonstrated here in the newsgroups, but cannot find it 
> now. Can someone help me please?
> 
> I would like to do something like this:
> 
> template MyTemplate(T)
> {
>   struct T ~ "Struct"  // define FooStruct structure
>   {
>     int x;
>   }
>   class T ~ "Class"  // define FooClass class
>   {
>     void bar(T ~ "Struct" t)
>     {
>       // ...
>     }
>   }
> }
> 
> void main()
> {
>   mixin MyTemplate!("Foo");
>   FooStruct t;
>   FooClass f = new FooClass();
>   f.bar(t);
> }
> 
> Hopefully I am not mistaken.

I don't know for what you're asking, but there's absolutely no need to 
use string mixins (see Trass3r's reply).

Instead you can just define a type inside the template, and then access 
it by instantiating it:

template MyTemplate(T) {
    struct Struct {
      T x;
    }
}

void main() {
    MyTemplate!(int).Struct t;
    t.x = 123;
}

You can use mixin MyTemplate!(int); to bring "Struct" into the module 
namespace, and you can use e.g. "alias MyTemplate!(int) IntStruct;" to 
save typing.


More information about the Digitalmars-d-learn mailing list