Pure, Nothrow in Generic Programming

Don nospam at nospam.com
Wed Nov 25 20:47:54 PST 2009


dsimcha wrote:
> One issue that should ideally be resolved before D2 is finalized that I meant
> to bring up here a long time ago is how to handle pure and nothrow in generic
> functions.  For example:
> 
> T max(T)(T lhs, T rhs) {
>     return (lhs > rhs) ? lhs : rhs;
> }
> 
> Obviously, if T is an int, max can be pure nothrow.  However, if T is some
> user defined type, then who knows?  I've run into a few cases where I'm
> writing a pure function that needs to call something simple like
> std.algorithm.max() on an int or a float and invariably I end up just
> rewriting a max function for my specific type and marking it as pure nothrow.
>  This is obviously a suboptimial solution.
> 
> Since the source needs to be available anyhow for templates to be usable, my
> proposal would be for pure/nothrow functions to be able to call templated
> functions that are not marked as pure/nothrow as long as they would compile if
> marked pure/nothrow. 

That sounds reasonable to me. Already in many cases, the function body 
must be analysed in order to determine the return type, so it must also 
be analysed to determine its pure/nothrow-ness. Implementation might be 
tricky, though.

  Also, I think that we need to establish a strong
> convention, for objects, that opCmp, opEquals and a few other "standard"
> functions should always be const pure nothrow, and that it is acceptable for
> any library code (mixins, etc.) to assume this.

And what about @safe ?

BTW, it worries me a little that safe, pure, and ability to be used in 
CTFE are concepts which have about 90% overlap. Yet none is a subset of 
another.



More information about the Digitalmars-d mailing list