Generic code: @autoconst, @autopure, @autonothrow

Jonathan M Davis jmdavisprog at gmail.com
Sat Aug 28 19:25:08 PDT 2010


On Saturday 28 August 2010 18:29:02 dsimcha wrote:
> An issue that comes up very frequently when trying to use const, pure or
> nothrow in generic code is lack of knowledge of whether the functions
> you're calling are const/pure/nothrow.  For example:
> 
> T abs(T num) pure nothrow {
>     return (num < 0) ? -1 * num : num;
> }
> 
> Looks pretty good.  Won't work with BigInt because opBinary!"*" isn't pure
> and can't practically be made pure.  A solution I propose is to allow the
> annotations @autoconst, @autopure and @autonothrow for template functions.
> These would mean "everything I do is const/pure/nothrow as long as all of
> the functions I call are const/pure/nothrow".  As far as I can tell, this
> would be reasonably implementable because the compiler always has the
> source code to template functions, unlike non-template functions.
> 
> A pure function would be allowed to call an @autopure function instantiated
> with a type that makes it pure, and similarly for const and nothrow. 
> Taking the address of an instantiation of an @autopure function would
> return a pure function pointer iff the instantiation was pure.  If an
> @autopure function tried to do anything impure other than call an impure
> function, ideally the result would not compile, since the function is
> falsely asserting that everything it does itself is pure.  This is not an
> absolute requirement, though.
> 
> I believe that this would massively simplify correctly using
> const/pure/nothrow in generic code, which currently is near impossible. 
> Does this sound like it could feasibly be implemented and would work well?

It certainly sounds good to me, though I'm probably not well enough versed on 
all the implications of const, nothrow, and pure to know exactly what effects 
this will have. Still, from where I sit, it sounds like a good idea.

- Jonathan M Davis


More information about the Digitalmars-d mailing list