Compile-Time Interfaces (Concepts)

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 23 10:53:09 PDT 2014


On Wed, Jul 23, 2014 at 05:09:54PM +0000, Bossfong via Digitalmars-d-learn wrote:
> On Wednesday, 23 July 2014 at 15:28:34 UTC, H. S. Teoh via
> Digitalmars-d-learn wrote:
> >On Wed, Jul 23, 2014 at 04:46:20PM +0200, bossfong via Digitalmars-d-learn
> >wrote:
[...]
> >>Still, maybe compiler errors could be provided by a library that
> >>defines an "Concept(Interface)" UDA that you could use to annotate
> >>implementations of "Concepts"?
> >>
> >>import concepts;
> >>
> >>@Concept(InputRange)
> >>struct MyInputRange
> >>{
> >>// ...
> >>}
> >>
> >>verifyConcepts();
> >>
> >>Is it that what you mean?
> >>
> >>Just thinking things through here...
> >
> >No, I'm talking about catching errors like this:
> >
> >	auto myRangeAlgo(R)(R range)
> >		if (isInputRange!R)
> >	{
> >		...
> >		auto r = range.save;	// <--- oops
> >		...
> >		return Result(...);
> >	}
> >
> >	unittest
> >	{
> >		auto testData = [1,2,3];
> >		auto result = myRangeAlgo(testData);
> >
> >		// Test will pass, because arrays are also forward
> >		// ranges, which have a .save method. So we fail to
> >		// catch the bug in the code above.
> >		assert(result.equal(expectedResults));
> >	}
> >
> >
> >T
> 
> What about a small wrapper struct then:
> A struct Concept that implements opdispatch and forwards all calls
> specified in the interface but for every other method do a pragma
> error.
> Then take this struct as a parameter in the function instead of any
> type T.  Maybe, if that is possible, allow implicit conversion from
> any type to Concept, so the callsite doesnt change.
> Is there something obvious im missing? Im justbrainstorming here...

That's not a bad idea, and in fact something similar occurred to me as
well. Basically, my idea was to create dummy structs representing the
Concepts checked by the sig constraints, and have unittests instantiate
the algorithm with said structs. The structs will only have the methods
defined by the Concept, so this will catch any wrong code that tries to
access something outside of what the Concept defines.

Your idea is better, in fact, since you wouldn't have to rely on
programmer diligence to write such unittests. You wouldn't even need to
use pragma error; you just have opDispatch forward only the functions
implemented by the concept, and everything else will result in a "no
such field" error.

The only trouble is implicit conversion. I don't think the language
allows that right now, by design.


T

-- 
Question authority. Don't ask why, just do it.


More information about the Digitalmars-d-learn mailing list