opDispatch

Tobias Pankrath via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Dec 25 07:57:24 PST 2014


On Thursday, 25 December 2014 at 15:50:07 UTC, Danny wrote:
> Hi,
>
> I'm trying to learn how opDispatch works. Unfortunately, a very 
> simple example already doesn't work (error: no property 'a' for 
> type 'Foo'):
>
> import std.stdio : writeln;
>
> struct X {
> 	int a;
> }
> class Foo {
> 	X value;
> 	template opDispatch(string s) {
> 		value.opDispatch!(s) opDispatch;
> 	}
> }
> int main() {
> 	auto f = new Foo;
> 	writeln(f.a);
> 	return 0;
> }
>
> What am I missing?
>
> Is there another way to make Foo forward all unknown things to 
> X ?

I am not sure why your code even compiles, but this works better:

import std.stdio;

struct X
{
     int a;
}

class XX
{
     X value;
     auto opDispatch(string s)() {
        mixin("return value." ~ s ~ ";");
     }
}

void main() {

     XX x = new XX();
     writeln(x.a);
}



More information about the Digitalmars-d-learn mailing list