www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Handle FormatSpec!char in the virtual toString() method of a class.

reply realhet <real_het hotmail.com> writes:
Hello,

Is there a way to the following thing in a class instead of a 
struct?

--------------------------------------
static struct Point
{
     int x, y;

     void toString(W)(ref W writer, scope const ref 
FormatSpec!char f)
     if (isOutputRange!(W, char))
     {
         // std.range.primitives.put
         put(writer, "(");
         formatValue(writer, x, f);
         put(writer, ",");
         formatValue(writer, y, f);
         put(writer, ")");
     }
}
--------------------------------------

I think the problem is that the toString() in a class is virtual, 
and don't let me to have multiple overloaded methods.

Is there a way to let format() deal with classes too?

Thank You!
May 13 2020
parent reply "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
On Wed, May 13, 2020 at 12:26:21PM +0000, realhet via Digitalmars-d-learn wrote:
 Hello,
 
 Is there a way to the following thing in a class instead of a struct?
 
 --------------------------------------
 static struct Point
 {
     int x, y;
 
     void toString(W)(ref W writer, scope const ref FormatSpec!char f)
     if (isOutputRange!(W, char))
     {
         // std.range.primitives.put
         put(writer, "(");
         formatValue(writer, x, f);
         put(writer, ",");
         formatValue(writer, y, f);
         put(writer, ")");
     }
 }
 --------------------------------------
 
 I think the problem is that the toString() in a class is virtual, and
 don't let me to have multiple overloaded methods.
 
 Is there a way to let format() deal with classes too?
[...] The main issue is that template functions cannot be virtual. So to make it work for classes, you need to forward toString to a virtual function implemented by subclasses. Here's one way to do it: class Base { // virtual method implmented by subclasses abstract void toStringImpl(scope void delegate(const(char)[]) sg, scope const ref FormatSpec!char f); void toString(W)(ref W writer, scope const ref FormatSpec!char f) { // forward to virtual method toStringImpl((s) => formattedWrite(writer, s), f); } } T -- If you want to solve a problem, you need to address its root cause, not just its symptoms. Otherwise it's like treating cancer with Tylenol...
May 14 2020
parent realhet <real_het hotmail.com> writes:
On Thursday, 14 May 2020 at 19:01:25 UTC, H. S. Teoh wrote:
 On Wed, May 13, 2020 at 12:26:21PM +0000, realhet via 
 Digitalmars-d-learn wrote:
Thank You, very helpful!
May 19 2020