opDispatch and compile time parameters

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 13 20:10:59 PST 2015


On 10/18/15 9:00 PM, David Osborne wrote:
> 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.
>

I just came across a need for this, thanks.

Is it me, or is this a bug?

struct Foo
{
    template opDispatch(string s) {
       // if you uncomment this, it compiles
       //void opDispatch() {}
       void opDispatch(T...)() {}
    }
}

void main()
{
    Foo f;
    f.blue!char(); // Error: no property 'blue' for type 'Foo'
}

-Steve


More information about the Digitalmars-d mailing list