opDispatch and compile time parameters

David Osborne via Digitalmars-d digitalmars-d at puremagic.com
Sun Oct 18 18:00:51 PDT 2015


On Saturday, 17 October 2015 at 15:31:00 UTC, Nikolay wrote:
> I asked on SO question about opDispatch and compile time 
> parameters: 
> http://stackoverflow.com/questions/32998781/opdispatch-and-compile-time-parameters
> [...]
> Is it good idea for opDispatch improvement or may there is some 
> other approach?

I must have my answer not too long after you made this thread, 
but there is another approach:
(copied from SO)

You need to use the eponymous template pattern, and have an 
opDispatch function with your compile-time parameters inside an 
outer opDispatch template that takes the regular opDispatch 
string parameter. You can also have multiple inner opDispatch 
functions (and fields) that follow regular overload rules.


     import std.stdio;

     struct Foo {

         public template opDispatch(string name) {

             public string opDispatch() {
                 return name;
             }

             public T opDispatch(T)() {
                return T.init;
             }

             public string opDispatch(T)(string s) {
                 return name ~ ' ' ~ T.stringof ~ ' ' ~ s;
             }
         }
     }

     void main()
     {
         Foo foo;
         writeln( foo.bar );
         writeln( foo.baz!int );
         writeln( foo.foo!Foo("foo") );
     }

Produces the output:

     bar
     0
     foo Foo foo

DPaste link: http://dpaste.dzfl.pl/6e5cfca8b702


I haven't fully explored the limitations of this approach, but it 
does work for simple cases.



More information about the Digitalmars-d mailing list