auto: useful, annoying or bad practice?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri May 11 18:44:25 UTC 2018


On Fri, May 11, 2018 at 04:57:05PM +0000, Mark via Digitalmars-d wrote:
> On Wednesday, 9 May 2018 at 15:06:55 UTC, Jonathan M Davis wrote:
> > Ultimately, the key is that the user of the function needs to be
> > able to know how to use the return type. In some cases, that means
> > returning a specific type, whereas in others, it means using auto
> > and being clear in the documentation about what kind of API the
> > return type has. As long as the API is clear, then auto can be
> > fantastic, but if the documentation is poorly written (or
> > non-existant), then it can be a serious problem.
> > 
> > - Jonathan M Davis
> 
> He also needs to know what requirements the parameters of the function
> should satisfy. We have template constraints for that, even though
> that could also have been "implemented" through documentation.

This makes me wonder if it might be useful to have return-type
constraints.  A kind of static out-contract?  Something that's part of
the function declaration, that ensures that the return type satisfies
certain properties.

	// Hypothetical syntax
	auto myfunc(R)(R r)
	if (isInputRange!R &&
		isOutputRange!return)
	{
		... // implementation here
	}

The `isOutputRange!return` (this is just tentative syntax, you guys can
probably think of better ways of writing this) statically enforces that
the return type must satisfy `isOutputRange`, and, being part of the
function signature, documents to the user what to expect of it.

Could be valuable.

Of course, we could repurpose existing out contracts for this, e.g.:

	auto myfunc(R)(R r)
	if (isInputRange!R)
	out(r) { static assert(isOutputRange!(typeof(r))); }
	do
	{
	}

A little more verbose, and has issues with the semantics of -release,
etc., but at least it gets the point across.


T

-- 
In order to understand recursion you must first understand recursion.


More information about the Digitalmars-d mailing list