[phobos] A few minor features
Walter Bright
walter at digitalmars.com
Sun Oct 31 16:38:03 PDT 2010
David Simcha wrote:
>
> The functionality is:
>
> 1. Static array literals that are guaranteed to avoid heap allocations:
>
> /**
> Creates a static array literal, avoiding the heap allocation that results
> from a regular array literal.
> */
> CommonType!(T)[T.length] staticArray(T...)(T elems)
> if(is(CommonType!(T))) {
> typeof(return) ret = void;
> foreach(i, Unused; T) {
> ret[i] = elems[i];
> }
>
> return ret;
> }
I'd prefer fixing that in the compiler, I just haven't gotten around to
it yet.
>
> 2. A function that allows the address of a nested function to be
> taken w/o a heap allocation.
>
> /**
> Allows the address of a nested function to be (unsafely) taken without
> resulting in a heap allocation.
> */
> T scopeAddress(T)(scope T val) {
> return val;
> }
>
> Usage:
>
> void fun() {
> void nested() {}
>
> auto addr = scopeAddress(&nested);
> }
>
> 3. An alwaysAssert() function that stays on in release mode but is
> otherwise equivalent to assert(). I had been using enforce() for
> this, but I don't like that anymore because it throws Exception, not
> AssertError by default. This means that if I write catch(Exception),
> I could accidentally be catching what is effectively an assertion
> failure. Since assert() is supposed to be terse to encourage the
> programmer to use it liberally, explicitly passing AssertError to
> enforce() doesn't cut it. Mostly what I need here is a better/terser
> name than alwaysAssert(). Given the nature of this feature, I'd say
> terseness actually beats explicitness. The best I've come up w/ so
> far is rassert() for release assert.
>
So far, what I use for this is:
if (!condition) assert(0);
Even in release mode, assert(0) will execute a HLT instruction.
More information about the phobos
mailing list