Template constraints

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Sat Feb 14 09:00:33 PST 2015


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


More information about the Digitalmars-d mailing list