Is there any writeln like functions without GC?

Ferhat Kurtulmuş aferust at gmail.com
Thu Oct 31 13:30:41 UTC 2019


On Thursday, 31 October 2019 at 03:56:56 UTC, lili wrote:
> Hi:
>    why writeln need GC?

I cannot answer why it needs GC but something can be implemented 
like:

import core.stdc.stdio;

struct Point {
     int x;
     int y;
}

class Person {
     string name;
     uint age;
}

template GenStructMemberPrint(string structInstanceName, string 
memberName){
     const char[] GenStructMemberPrint = "printf(\"%d\", " 
~structInstanceName ~ "." ~ memberName ~ ");"; // static ifs can 
be used to use proper formats depending on the typeof struct 
member
}

// entire thing can be implemented using sprintf to obtain a nice 
formatted line
void writeln2(A...)(A arguments) @nogc nothrow {
     foreach (a; arguments) {
         static if (is(typeof(a) == class) || is(typeof(a) == 
interface)) {
             printf("%s \n", typeof(a).stringof.ptr);
         } else
             static if (is(typeof(a) == string)) {
             printf("%s \n", a.ptr);
         } else
         static if (is(typeof(a) == struct)){
             foreach (member; __traits(allMembers, typeof(a))) {
                 //writeln(member);
                 mixin(GenStructMemberPrint!(a.stringof, member)); 
// this needs some improvements to imitate writeln
             }
         }
         else {
             static assert( "non-supported type!");
         }
     }

}

void main()
{
     auto pt = Point(10, 20);
     auto per = new Person(); // nogc custom allocator can be used 
here
	
     writeln2("ssss", per, pt);
}




More information about the Digitalmars-d-learn mailing list