Template constraints error messages using cputs()

bearophile bearophileHUGS at lycos.com
Fri Aug 6 08:56:47 PDT 2010


In D1 there were no template constraints, so to test the template arguments I used to add some static asserts inside them. So a wrong template argument shows a error message written by me that explains why the instantiation has failed (unfortunately those error messages show the line number inside the template).

When a template constraint is composed of some different parts in &&, it's less easy to understand what condition has failed, so I miss the error messages written by me. This is an example (that probably I will simplify), there are four conditions, and for a person that has not written this code, and is just using Phobos, it's not immediately obvious what part has failed:


auto opBinary(string op, TOther)(TOther other)
  if (op == "~" && is(TOther == struct) &&
      (!__traits(compiles, { void isTuple(U...)(Tuple!U){} isTuple(other); }) ||
       distinctFieldNames!(T, TOther.TypesAndStrings)() )) { ...


There is a simple solution. The simple template constraints often don't need extra error messages, so they can be left as they are now.

Putting one or more error message inside a template constraints turns them into messy code, so in such cases it's better to move the tests elsewhere, in an external template/CTFE:

template IsGoodFoo(T) {
    static if (...) {
        enum bool IsGoodFoo = true;
    } else {
        ctputs("this is an error message");
        return false;
    }
}

void foo(T)(T x) if (IsGoodFoo!T) { ...


So the ctputs() I have suggested here is usable for the template constraints error messages too (this 3952 is in truth a bug report and enhancement request fused in one, later Brad has explained me to avoid this):
http://d.puremagic.com/issues/show_bug.cgi?id=3952

This shows one more purpose for ctputs().
Later I will add those comments to the bug 3952.

Bye,
bearophile


More information about the Digitalmars-d mailing list