Thread overview
override to!string
Feb 25, 2011
spir
Feb 25, 2011
Jesse Phillips
Feb 25, 2011
Dmitry Olshansky
February 25, 2011
Hello,

Imagine I have the following custom type:
	alias float[] Numbers;

Is it possible to override to!string for Numbers so that it outputs eg like;
	(1.1 2.2 3.3)
?

I can indeed override/specialise toImpl or formatValue for the custom type, but those overrides are simply ignored (tested).

Denis
-- 
_________________
vita es estrany
spir.wikidot.com

February 25, 2011
spir Wrote:

> Hello,
> 
> Imagine I have the following custom type:
> 	alias float[] Numbers;
> 
> Is it possible to override to!string for Numbers so that it outputs eg like;
> 	(1.1 2.2 3.3)
> ?

No, this is one reason for writeTo replacing toString, or whatever the name. It would allow a formatter specified. I don't really know how to! would be changed to fit into that.


> I can indeed override/specialise toImpl or formatValue for the custom type, but those overrides are simply ignored (tested).

Right, that would be anti-hijacking at work. Don't want behavior changed because you imported a module. You might be able to override to itself though.

Otherwise you can use format specifiers from std.string.format.
February 25, 2011
On 25.02.2011 17:28, spir wrote:
> Hello,
>
> Imagine I have the following custom type:
>     alias float[] Numbers;
>
> Is it possible to override to!string for Numbers so that it outputs eg like;
>     (1.1 2.2 3.3)
> ?
>
> I can indeed override/specialise toImpl or formatValue for the custom type, but those overrides are simply ignored (tested).
>
> Denis

First things first, it's just an alias and not a custom type. So compiler won't distinguish between float[] and Numbers at all.
The obvious way around is make your own thin wrapper, but yeah, it won't get format specifiers until writeTo or similar proposal implemented.

import std.stdio,std.conv;
struct Numbers{
    float[] data;
    string  toString(){
        string result = "(";
        foreach(val;data[0..$-1]){
            result ~= to!string(val);
            result ~= ' ';
        }
        result ~= to!string(data[$-1]);
        result ~= ')';
        return result;
    }
    alias data this;
}

Usage:
void main(){
    Numbers nums = Numbers([1.1,2.2,3.3]);
    writefln("%s",nums);
    nums[0] = 4.4;
    writefln("%s",nums);
}

-- 
Dmitry Olshansky