Template constraints

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Mon Feb 16 11:31:19 PST 2015


On 2/14/15 12:00 PM, Andrei Alexandrescu wrote:
> There's been recurring discussion about failing constraints not
> generating nice error messages.
>
> void fun(T)(T x) if (complicated_condition) { ... }
> struct Type(T)(T x) if (complicated_condition) { ... }
>
> If complicated_condition is not met, the symbol simply disappears and
> the compiler error message just lists is as a possible, but not viable,
> candidate.
>
> I think one simple step toward improving things is pushing the condition
> in a static_assert inside type definitions:
>
> void fun(T)(T x) if (complicated_condition) { ... } // no change
> struct Type(T)(T x)
> {
>    static assert(complicated_condition, "Informative message.");
>    ...
> }
>
> This should improve error messages for types (only). The rationale is
> that it's okay for types to refuse compilation because types, unlike
> functions, don't overload. The major reason for template constraints in
> functions is allowing for good overloading.
>
>
> Andrei

Wait, isn't this OK?

struct S(T) if(is(T == int))
{
   ...
}

struct S(T) if(is(T == double))
{
   ...
}

I mean we could do it like this:

struct S(T)
{
   static if(is(T == int))
   {
      ... // int mode
   }
   else static if(is(T == double))
   {
      ... // double mode
   }
   else static assert(0);
}

but that defeats the purpose of being able to split the "int mode" stuff 
from the "double mode" stuff. They may even be in multiple modules.

Is this not "overloading" of types? I don't think this should be frowned 
upon.

I think instead of this, we should try and just make the messages 
better. Note that something like you are suggesting requires much 
rewriting of code.

Have you considered something like this? 
forum.dlang.org/post/m4nnrk$1ml5$1 at digitalmars.com

-Steve


More information about the Digitalmars-d mailing list