www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Constraints error messages [Was: Re: Constrained Templates]

reply bearophile <bearophileHUGS lycos.com> writes:
Yao G.:

 Something I would like to see with template constraints, is the ability to  
 show text messages, like when static if is used.

This is a problem I too have. In D1 I used to write code like: template Foo(T) { static assert(condition1, "error message1"); static assert(condition2, "error message2"); ... } Now in D2 I usually write: template Foo(T) if (condition1 && condition2) { ... } This D2 code is better because error compiler messages are better (at the template instantiation point instead inside the template body), but it's worse because I lose the error messages written by me. In simple situations the error messages are not so important, but in some situations they are useful to understand why the template input values are wrong. A syntax like the following allows to add the user-defined error messages too, but it's bad looking, so probably something quite better can be invented: template Foo(T) if (condition1) else pragma(msg, "error message1") if (condition2) else pragma(msg, "error message2") { } Bye, bearophile
Jun 14 2010
parent reply BCS <none anon.com> writes:
Hello bearophile,

 A syntax like the following allows to add the user-defined error
 messages too, but it's bad looking, so probably something quite better
 can be invented:
 
 template Foo(T)
 if (condition1) else pragma(msg, "error message1")
 if (condition2) else pragma(msg, "error message2") {
 }

I like the idea, but how should it interact with overloaded templates? template Foo(T) if(cond1!T) else pragma(msg, "a") {} template Foo(T) if(cond2!T) else pragma(msg, "b") {} Don't run any of the elses unless all the options fail and then run all of them? -- ... <IXOYE><
Jun 14 2010
parent bearophile <bearophileHUGS lycos.com> writes:
BCS:

I like the idea, but how should it interact with overloaded templates?<

The syntax/semantics I have shown is just a starting point, there are probably way better ways to reach the same goal. For example a kind of run-time error/exception for templates that shows an error message and removes the template from the list of possible templates. Regarding overloaded templates, those else clauses are meant to be useful mostly when there is no template overloading, they are designed to be useful not for the usual purpose of constrains, that is to remove templates from the pool of overloads, but mostly when you have a single template that has input types and values that must satisfy some requirements. So it's a grubby idea that needs more thinking :-) Bye, bearophile
Jun 15 2010