Template question

Derek Parnell derek at nomail.afraid.org
Wed Oct 4 21:47:20 PDT 2006


On Wed, 04 Oct 2006 15:52:01 -0400, Chad J wrote:

> I'm trying to write a template that, when instantiated, gives a value 
> that is the same as the last time it was instantiated plus one.  

This does not answer your question, but I was wondering why you need this
functionality at compile time. I do something similar but it happens at
application initialization time and is simple to code.

 import util.series;
 import std.stdio;

 Series UID; // Declare the series.
 static this()
 {
   UID.Next = 1; // Set first value to one.
 }

 void main()
 {
     writefln( UID.Next ); // should print 1
     writefln( UID.Next ); // should print 2
 }

Where series.d is 

// ------------------
module util.series;

struct Series
{
    private
    {
        ulong mValue;
        ulong mIncr;
    }

    ulong Next()
    {
        ulong lCV;

        lCV = mValue;
        mValue += (mIncr+1);
        return lCV;
    }

    void Next(ulong pInit)
    {
        mValue = pInit;
    }

    ulong Current()
    {
        return mValue;
    }

    ulong Prev()
    {
        return mValue - (mIncr+1);
    }

    void Increment(ulong pInit = 1)
    {
        mIncr = pInit-1;
    }

}


unittest
{
    Series a;
    assert( a.Next == 0);
    assert( a.Next == 1);
    assert( a.Next == 2);
    assert( a.Current == 3);
    a.Increment = 2;
    assert( a.Next == 3);
    assert( a.Next == 5);
    assert( a.Prev == 5);
    a.Next = 100;
    assert( a.Current == 100);
    assert( a.Next == 100);
    assert( a.Next == 102);
}

// ------[ end of file ]-----------------


-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
5/10/2006 2:15:46 PM



More information about the Digitalmars-d-learn mailing list