On Monday, 14 May 2012 at 06:04:33 UTC, Mehrdad wrote:
On Monday, 14 May 2012 at 03:19:57 UTC, Jonathan M Davis wrote:
I suspect that the folks who are looking for absolutely every
CPU cycle and want caching and lazy-loading in their types
It's not a CPU cycle issue.
Caching/lazy-loading can make the difference between a window
that freezes, and a window that doesn't.
You can still do this pretty easily. You just have to cast away
const.
You can even make it reusable.
mixin template TrustedToString() {
const @safe pure nothrow string toString() {
return unsafeToString();
}
final const @trusted pure nothrow string unsafeToString() {
auto nonConstThis = cast(Unqual!(typeof(this)))this;
return nonConstThis.trustedToString();
}
}
class Foo {
public:
const @safe pure nothrow string toString() {
return "Foo";
}
}
class Bar : Foo {
public:
mixin TrustedToString;
final pure @trusted nothrow string trustedToString() {
if (cachedString.length == 0) {
cachedString = "Bar";
}
return cachedString;
}
string cachedString;
}
unittest {
auto f = new Foo();
assert(f.toString() == "Foo");
auto b = new Bar();
assert(b.toString() == "Bar");
}