April 19, 2013
On 04/19/2013 01:35 PM, gedaiu wrote:

> Ok, i understand now the diference...
>
> my question is how I should solve this problem?

The keyword 'override' cannot be used with structs. You have at least two good options with structs:

1) Define a const toString() member function that returns the string representation of the object, conveniently produced by std.string.format:

import std.stdio;
import std.string;

struct TimeOfDay
{
    int hour;
    int minute;

    string toString() const
    {
        return format("%02s:%02s", hour, minute);
    }
}

void main()
{
    auto t = TimeOfDay(10, 20);
    writeln(t);
}

2) As the previous method is unnecessarily inefficient especially when the members are structs as well, define the toString() overload that takes a sink delegate. std.format.formattedWrite is smart enough to take advantage of it and avoids multiple string instances. Everything gets appended to the same output string:

import std.stdio;
import std.format;

struct TimeOfDay
{
    int hour;
    int minute;

    void toString(scope void delegate(const(char)[]) output) const
    {
        formattedWrite(output, "%02s:%02s", hour, minute);
    }
}

struct Duration
{
    TimeOfDay begin;
    TimeOfDay end;

    void toString(scope void delegate(const(char)[]) output) const
    {
        formattedWrite(output, "from %s to %s", begin, end);
    }
}

void main()
{
    auto d = Duration(TimeOfDay(10, 20), TimeOfDay(11, 22));
    writeln(d);
}

Ali

1 2
Next ›   Last »