opApply and const

Christopher Wright dhasenan at gmail.com
Sun Dec 9 08:14:22 PST 2007


Daniel Keep wrote:
> My apologies.  It *does* actually support arbitrary opApply()s.  What
> probably *doesn't* support are types with more than one opApply.  Can we
> get a list of overloads with D 2.0 yet?
> 
> 	-- Daniel

In the general case: no.
If you're only concerned about the virtual ones: yes, with 
__traits(getVirtualFunctions). (I think that's it; I always forget what 
it is exactly.)


> module enumerate;
> 
> import std.stdio;
> import std.traits;
> 
> struct Enumerate(T)
> {
>     private
>     {
>         T source;
>         alias ParameterTypeTuple!(typeof(T.opApply))[0] opApply_arg;
>         alias ParameterTypeTuple!(opApply_arg) opApply_type;
>     }
> 
>     int opApply(int delegate(ref size_t, opApply_type) dg)
>     {
>         int result = 0;
>         size_t i = 0;
> 
>         foreach( ref opApply_type x ; source )
>         {
>             if( (result=dg(i,x)) != 0 ) break;
>             ++i;
>         }
>         return result;
>     }
> }
> 
> Enumerate!(T) enumerate(T)(T source)
> {
>     return Enumerate!(T)(source);
> }
> 
> class Foo
> {
>     static const words = ["On"[],"a","Sunday,","riding","my","bike"];
> 
>     int opApply(int delegate(ref char[]) dg)
>     {
>         int result = 0;
>         foreach( word ; words )
>             if( (result=dg(word)) != 0 ) break;
>         return result;
>     }
> }
> 
> class Bar
> {
>     int opApply(int delegate(ref real, ref char[]) dg)
>     {
>         // Nasty code:
>         real r; char[] d;
>         r = 3.14159;    d = "pi"; dg(r,d);
>         r = 3.0;        d = "pi (according to the Bible)"; dg(r,d);
>         r = 42.0;       d = "meaning of life"; dg(r,d);
>         r = real.nan;   d = "how much wood would a wood chuck chuck?";
> dg(r,d);
>         return 0;
>     }
> }
> 
> void main()
> {
>     foreach( word ; new Foo )
>         writef("%s ",word);
>     writefln("");
> 
>     writefln("");
> 
>     foreach( i,word ; enumerate(new Foo) )
>         writefln("[%s] %s", i, word);
> 
>     writefln("");
> 
>     foreach( r,desc ; new Bar )
>         writefln("%s: %s", r, desc);
> 
>     writefln("");
> 
>     foreach( i,r,desc ; enumerate(new Bar) )
>         writefln("[%s] %s: %s", i, r, desc);
> }



More information about the Digitalmars-d mailing list