Simple IFTI use

Sean Kelly sean at f4.ca
Sun Apr 2 22:39:40 PDT 2006


Kevin Bealer wrote:
> Often when working with D arrays, I miss the "doubling" effect of push_back from
> C++ std::vector.  With IFTI, this is possible (trivial, really) in D.  I put
> some code here - the idea is to use existing arrays, no special classes, but
> have an "append" functionality, like vector::push_back().
> 
> : // -*- c++ -*-
> :
> : import std.string;
> :
> : template push_back(T) {
> :     // The first arg is inout only for performance reasons.
> :
> :     void push_back(inout T elem, inout T[] vec, inout int vsize)
> :     {
> :         assert(vec.length >= vsize);
> :
> :         if (vec.length != vsize) {
> :             vec.length = (vec.length
> :                           ? vec.length * 2
> :                           : 4); // arbitrary
> :         }
> :
> :         vec[vsize++] = elem;
> :     }
> : };
> :
> : // Usage
> :
> : import simplevec;
> :
> : Foo[] stuff; int stuff_size;
> :
> : Foo f = new Foo;
> :
> : push_back(f, stuff, stuff_size);

If you flip the parameters:

void push_back( inout T[] vec, T elem )

The array trick could be used to call it like so:

f.push_back( stuff );

This would obviously also require an overload that doesn't take a third 
parameter.

Sean



More information about the Digitalmars-d mailing list