rval->ref const(T), implicit conversions

tsbockman via Digitalmars-d digitalmars-d at puremagic.com
Mon Jan 18 09:57:26 PST 2016


On Monday, 18 January 2016 at 15:36:09 UTC, Manu wrote:
> One more time...
>
> Assuming:
> void func(const CustomString &s1, const CustomString &s2);
> void func(ref const(CustomString) s1, ref const(CustomString) 
> s2);
>
> C++:
>   func("hello", "world");
>
> D:
>   auto dumb_name = CustomString("hello");
>   auto another_dumb_name = CustomString("world");
>   func(dumb_name, another_dumb_name);

Does this do what you want?

import std.stdio;

bool isLValue(T)(ref T val) {
     return true;
}

struct CustomString {
     this(string data) {
         this.data = data;
     }

     string data;
     alias data this;
}

void func(ref CustomString s1, ref CustomString s2) {
     writeln(s1);
     writeln(s2);
     s2 = "universe!";
}

pragma(inline, true)
void arFunc(T, V)(auto ref T s1, auto ref V s2) {
     static if(__traits(compiles, isLValue(s1)))
         alias s1L = s1;
     else
         T s1L = s1;

     static if(__traits(compiles, isLValue(s2)))
         alias s2L = s2;
     else
         V s2L = s2;

     func(s1L, s2L);
}


void main() {
     CustomString b = CustomString("world!");
     arFunc(CustomString("Hello"), b);

     writeln("Hello");
     writeln(b);
}

If so, I probably genericize arFunc better so you can just do 
this:

void funcImpl(ref const(CustomString) s1, ref const(CustomString) 
s2);
alias func = arFunc!funcImpl;



More information about the Digitalmars-d mailing list