On 07/16/2013 01:40 PM, JS wrote:

> The problem is I can't declare my "global" int variables directly inside
> the template. This does make it hard to use the same variable across
> multiple functions...
>
> template A
> {
>      int c; // makes c near useless, can't use it like a normal it...
> }

Could you please provide complete code. The following works:

import std.stdio;
import std.conv;

template A()
{
    int c;
}

string func(T)()
{
    string result;

    alias counter = A!().c;

    for ( ; counter < 10; ++counter) {
        result ~= counter.to!string;
    }

    return result;
}

void main()
{
    writeln(func!int());
}

Prints:

0123456789

This works as well:

import std.stdio;
import std.conv;

template A()
{
    int c;

    string func()
    {
        string result;

        for ( ; c < 10; ++c) {
            result ~= c.to!string;
        }

        return result;
    }
}

void main()
{
    writeln(A!().func());
}

Prints the same:

0123456789

> the error message given obfuscates the reason.

What is the error message?

> Unfortunately it requires a messy technique to get around by using nested
> functions. (The parent function holds the global state of the child
> functions)

Well, this works as well:

import std.stdio;
import std.conv;

template A()
{
    int c;

    string globalFunc()
    {
        string result;

        void func()
        {
            for ( ; c < 10; ++c) {
                result ~= c.to!string;
            }
        }

        func();
        return result;
    }
}

void main()
{
    writeln(A!().globalFunc());
}

Again, prints the same:

0123456789

> It would be nice if we had some way to data globally(in module).
>
> e.g., __ctfestore["name"] = value;

I would expect model-level objects start their lives after the program starts running but their initial value can be calculated during compile time:

import std.stdio;
import std.conv;

int[string] ctfestore;

static this()
{
    ctfestore = A!().globalFunc();
}

template A()
{
    int c;

    int[string] globalFunc()
    {
        int[string] result;

        void func()
        {
            for ( ; c < 10; ++c) {
                result[c.to!string] = c;
            }
        }

        func();
        return result;
    }
}

void main()
{
    writeln(ctfestore);
}

Prints:

["0":0, "4":4, "8":8, "1":1, "5":5, "9":9, "2":2, "6":6, "3":3, "7":7]

Ali

Reply via email to