www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - override to!string

reply spir <denis.spir gmail.com> writes:
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
Feb 25 2011
next sibling parent Jesse Phillips <jessekphillips+D gmail.com> writes:
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.
Feb 25 2011
prev sibling parent Dmitry Olshansky <dmitry.olsh gmail.com> writes:
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
Feb 25 2011