How to turn this C++ into D?

luminousone via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Nov 5 09:44:58 PST 2014


On Wednesday, 5 November 2014 at 17:17:11 UTC, Patrick Jeeves 
wrote:
> So this is more a stackoverflow question, but I feel like later 
> searchers will be more likely to find it if I put it here.
>
> if I have the following C++ code:
>
> class foo
> {
> static std::list<foo*> foo_list;
> typedef std::list<foo*>::iterator iterator;
> public:
>     foo()
>     {
>        foo_list.push_back(this);
>     }
>     ~foo()
>     {
>        foo_list.remove(this);
>     }
>
>     static void DO_TASK()
>     {
>         for(iterator i = foo_list.begin(); i < foo_list.end(); 
> ++i)
>         {
>             (*i)->process();
>         }
>
>         for(iterator i = foo_list.begin(); i < foo_list.end(); 
> ++i)
>         {
>             (*i)->advance();
>         }
>     }
>
>     virtual void process() = 0;
>     virtual void advance() = 0;
> }
>
> How can I turn this into D?  Is there a way to register that 
> static list with the garbage collector so it doesn't look into 
> it or anything?
>
> Similarly, I feel like this would be an interface in D, but 
> interfaces don't have constructors.

abstract class foo {
     static DList!foo foo_list;
     this() {
         if( foo_list is null )
             foo_list = make!(DList!foo);
         foo_list.insert(this);
     }
     ~this(){ foo_list.remove(this); }
     static void DO_TASK() {
         foreach( i ; foo_list ) { i.process(); }
         foreach( i ; foo_list ) { i.advance(); }
     }
     abstract void process();
     abstract void advance();
}

note that static is thread local in D, so foo_list would be 
unique per thread, if you want it globally unique then you need 
to pull it out of the class and market it

__gshared foo_list;

Also no need to mark functions as virtual, as dlang is currently 
virtual by default rather then final by default, for best 
optimization be sure to mark functions as final when possible.


More information about the Digitalmars-d-learn mailing list