Operator overloading question

Ali Çehreli acehreli at yahoo.com
Mon Jan 21 09:16:21 PST 2013


On 01/21/2013 08:32 AM, mist wrote:

 > phobos style
 > guidelines favor constraints heavily over static asserts but this
 > exactly the example when I am uneasy about such choice: static assert
 > can both provide more user-friendly error message here and remove some
 > code duplication.

Agreed but there is a problem with 'static assert' in the 
implementation: We don't know what user code has caused the issue. (It 
is a common problem in C++ templated libraries that a hard-to-understand 
compilation error is produced from inside a library function template.)

D's template constraints move the compilation error to the exact place 
of the user code.

void foo(string s)()
     if ((s == "hello") || (s == "goodbye"))
{
     // ...
}

void main()
{
     foo!"howdy"();  // <-- compilation error on this line
}

It is better:

Error: template instance foo!("howdy") foo!("howdy") does not match 
template declaration foo(string s)() if (s == "hello" || s == "goodbye")

To be honest, it is kind of obvious in this simple case but sometimes 
the cause of the error is still hard to understand even with template 
consraints.

Ali



More information about the Digitalmars-d-learn mailing list