Compile-time reference type objects construction (Was - Re: struct inheritance need?)

Denis Koroskin 2korden at gmail.com
Sun Dec 21 09:41:28 PST 2008


On Sun, 21 Dec 2008 19:34:52 +0300, Kagamin <spam at here.lot> wrote:

> Derek Parnell Wrote:
>
>> I think he wants to have some objects constructed at compile-time.
>
> Sure he wants. From my point of view, this technique is supposed to be a  
> means to solve some problem rather than problem itself. But this problem  
> was not put.

Ok, here is a problem out of my head:

Let's say we have a GUI application with Widgets and WidgetFactories. Each widget is initialized with a *valid* pointer to some WidgetFactory (a dummy one, perhaps) to avoid "if (factory !is null) factory.doSomething();" checks (for example). Our first try:

import std.stdio;

struct WidgetFactory
{
    int someParameterValue = 42;
}

WidgetFactory defaultFactory = { 14 }; 

class Widget
{
    WidgetFactory* factory = &defaultFactory;
}

void main()
{
    Widget w = new Widget();
    writefln(w.factory.someParameterValue); // prints 14
}

It works, because memory for global structs is reserved at compile time and pointer to it is also a known compile-time expression. Let's go further and see if we can replace a struct with a class instance:

WidgetFactory defaultFactory;

class Widget
{
    WidgetFactory factory = defaultFactory;
}

This code compiles but doesn't work as we need. Another try:

WidgetFactory defaultFactory;

static this()
{
    defaultFactory = new StubFactory();
}

class Widget
{
    WidgetFactory* factory = &defaultFactory;
}

Works as we need but we now have to dereference a pointer twice.

A better solution would be to have the following:

WidgetFactory defaultFactory = new StubFactory();

class Widget
{
    WidgetFactory factory = defaultFactory;
}

A memory for 'defaultFactory' is reserved at compile-time whereas a ctor is ran at run-time (similar to "static this" construct).
In fact, allowing reference type to created at compile time would eliminate most of the needs for static this. The following construct:

Foo foo;
static this()
{
    foo = new Foo();
}

could be replaced with

Foo foo = new Foo();

which behaves just the same but is shorter, nicier, easier to write and read (undestand).


More information about the Digitalmars-d-learn mailing list