Template constraints in D

Bill Baxter dnewsgroup at billbaxter.com
Sun Jun 22 15:35:47 PDT 2008


Walter Bright wrote:
> Bill Baxter wrote:
>> Still, anything containing __traits looks like an afterthought.
> 
> A bit.
> 
>> Also, I'm not sure how it's going to work in C++, but isn't the 
>> compiler going to have a hard time reporting errors in that kind of 
>> thing? Failure to instantiate could be because of a very minor typo in 
>> the big list of constraints.
> 
> True, you won't have an indication which failed. But you won't in C++, 
> either, because the overload just won't be matched.

Only true for C++ 'auto' concepts.
"""
The auto specifier means that any type which has a suitable operator<
will be considered LessThanComparable; if omitted, the user will have to 
explicitly state that her types meet the requirements of the concept 
using a concept map
"""

As I said after that, I'm thinking more about the non-auto case, where 
you specify a concept_map.

> 
>> I'm not sure how C++ will deal with that, but I think it's another 
>> place where concept maps help.  They introduce a little redundancy.  
>> They give you a place to say "I think type X satisfies concept Y, and 
>> here's how".  That gives the compiler a place to say, "No you're 
>> wrong, type X does not satisfy concept Y because Foo isn't actually a 
>> method of X".  It seems like it should be possible to generate very 
>> readable error messages from that.
> 
> Because you can overload based on concepts, I don't see how the compiler 
> can give an error message saying it failed to match part of a concept.

No, I mean when you have a concept_map the error can be generated at the 
point the concept_map is declared.  Telling the user the concept he 
thought he was implementing isn't being implemented.  I think in D you 
could do some variation of

    static assert(is(typeof(conceptStack!(Foo))),
                  "Foo doesn't implement Stack concept");

(using DeeGirl's template:
   void stackConcept(T)()
   {
       T t;
       T.value_type v = top(t);
       push(t, v);
       pop(t);
       if (empty(t)){}
   }
)

BUT the static assert will just tell you Foo does not qualify as a 
Stack, it won't tell you why.  Whereas the C++0x compiler with a concept 
map could tell you specifically what part of the concept is lacking.

But of course the main benefit of concept maps is that when I want to 
plug Vinces's Vector class into Larry's LinearSolver class all I have to 
do is specify how Vince's Vector satisfies Larry's VectorConcept.  And 
it doesn't matter if Vince overloaded opMul to mean dot product, but 
Larry expects a member named "dot".

Maybe if you haven't yet you could talk it over with Andrei.  My 
experience is that discussing things with you here on the NG is not all 
that productive because you only ever respond with one or two sentences, 
so that's all I'm going to say about this.

--bb



More information about the Digitalmars-d mailing list