Template method and type resolution of return type
matovitch via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Apr 19 11:46:26 PDT 2014
On Saturday, 19 April 2014 at 17:49:54 UTC, bearophile wrote:
> matovitch:
>
>> struct Test
>> {
>> immutable (ubyte)[] data;
>>
>> T get(T)()
>> {
>> return *(cast(T*)(&(data[0])));
>> }
>
> It's better to return const/immutable data. Otherwise the
> program gives undefined results. In alternative use mutable
> ubytes for data.
>
> Also &data[0] is probably data.ptr.
I did'nt know that one.
>
>
>> This won't compile :
>>
>> import std.stdio;
>>
>> void main()
>> {
>> Test t;
>> t.data = [152, 32, 64, 28, 95];
>> float b = t.get;
>> writefln("%s", b);
>
> D doesn't perform inference on the return type.
I see. But why ?
It's seems it exits a workaround overloading cast operators in
c++ :
http://programmaticallyspeaking.blogspot.se/2012/09/infer-return-type-for-templated.html
However I think it would only work with opImplicitCast in D. The
code given in vibe.d doc could became :
void manipulateJson(Json j)
{
j = Json.emptyObject;
j.name = "Example";
j.id = 1;
// retrieving the values is done using get()
assert(j["name"] == "Example");
assert(j["id"] == 1);
// print out as JSON: {"name": "Example", "id": 1}
writefln("JSON: %s", j.toString());
}
ps : Thank you for all your great examples on Rosetta code (or
the last one about the rubik's cube).
More information about the Digitalmars-d-learn
mailing list