digitalmars.D.learn - override to!string
- spir (13/13) Feb 25 2011 Hello,
- Jesse Phillips (4/14) Feb 25 2011 Right, that would be anti-hijacking at work. Don't want behavior changed...
- Dmitry Olshansky (29/39) Feb 25 2011 First things first, it's just an alias and not a custom type. So
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
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
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). DenisFirst 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