Compile-Time Interfaces (Concepts)

Bossfong via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 23 10:09:54 PDT 2014


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:
>> Am 23.07.2014 16:27, schrieb H. S. Teoh via 
>> Digitalmars-d-learn:
>> >
>> >We could, though it's not quite the same as a native concepts
>> >implementation where the compiler can check templates for 
>> >code that
>> >wrongly makes assumptions about the incoming type that aren't 
>> >defined by
>> >the concept.
>> >
>> >
>> >T
>> >
>> true.
>> 
>> 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...


More information about the Digitalmars-d-learn mailing list