On Saturday, 19 April 2014 at 18:46:28 UTC, matovitch wrote:
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).
Or even :
void manipulateJson(Json j)
{
j = Json.emptyObject;
j.name = "Example";
j.id = 1;
assert(j.name == "Example");
assert(j.id == 1);
// print out as JSON: {"name": "Example", "id": 1}
writefln("JSON: %s", j.toString());
}
Or at least this will work :
void manipulateJson(Json j)
{
j = Json.emptyObject;
j.name = "Example";
j.id = 1;
string s = j.name;
assert(s == "Example");
// print out as JSON: {"name": "Example", "id": 1}
writefln("JSON: %s", j.toString());
}
Ok I stop fooding.