Advertisement
beng

Template specialization and mixins

Mar 29th, 2013
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 2.06 KB | None | 0 0
  1. import std.stdio;
  2. import std.traits;
  3.  
  4. class Foo {
  5.   void go(T)(T t) { writefln("Foo.go(T)"); }
  6.   void go(T : int)(T t) { writefln("Foo.go(T : int)"); }
  7. }
  8.  
  9. // Declares just a specialization of go(T) given a type                                                                                                                                                                                      
  10. mixin template MakeGo(U) {
  11.   mixin("void go(T : " ~ fullyQualifiedName!(U) ~ ")(T t) {" ~
  12.         "writefln(\"MakeGo.go(T : U)\"); }");
  13. }
  14.  
  15. // Declares both go(T) and a specialization of go(T) given a type                                                                                                                                                                            
  16. mixin template MakeGo2(U) {
  17.   mixin("void go(T)(T t) { writefln(\"MakeGo2.go(T)\"); }\n" ~
  18.         "void go(T : " ~ fullyQualifiedName!(U) ~ ")(T t) { writefln(\"MakeGo2.go(T : U)\"); }");
  19. }
  20.  
  21. class Bar {
  22.   void go(T)(T t) { writefln("Bar.go(T)"); }
  23.   mixin("void go(T : int)(T t) { writefln(\"Bar.go(T : int)\"); }");
  24.   mixin MakeGo!(Foo);
  25. }
  26.  
  27. class Baz {
  28.   mixin MakeGo2!(Foo);
  29. }
  30.  
  31. void main() {
  32.   auto foo = new Foo();
  33.   foo.go("foo");
  34.   foo.go(0);
  35.  
  36.   auto bar = new Bar();
  37.   bar.go("bar");
  38.   bar.go(0);
  39.  
  40.   // XXX: This should call MakeGo.go(T : U), but it calls Bar.go(T) instead.                                                                                                                                                                
  41.   bar.go(foo);
  42.  
  43.   auto baz = new Baz();
  44.   // This correctly calls MakeGo2.go(T)                                                                                                                                                                                                      
  45.   baz.go("baz");
  46.  
  47.   // And this correctly calls MakeGo2.go(T : U)                                                                                                                                                                                              
  48.   baz.go(foo);
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement