Operator overloading question

Ali Çehreli acehreli at yahoo.com
Mon Jan 21 10:53:07 PST 2013


On 01/21/2013 10:02 AM, mist wrote:
 > Hm, but why can't static assert provide an instantiation trace? I can
 > live without error message

I forgot to mention that template constraints take part in choosing the 
implementation as well:

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

void foo(string s)()
     if (s == "howdy")
{
     // ...
}

void main()
{
     foo!"howdy"();    // not an error: goes to special implementation
     foo!"merhaba"();  // error: no implementation at all
}

In order to achieve the same goal without template constraints we have 
two options:

1) Template specialization, which I don't think is not valid for 
non-type template parameters like string:

void foo(string s == "hello")() // ERROR; I don't think possible
{
     // ...
}

2) 'static if' in the implementation:

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

     } else static if (s == "howdy") {
         // ...

     } else {
         static assert(false, "Invalid string " ~ s);
     }
}

void main()
{
     foo!"howdy"();
     foo!"merhaba"();
}

You are right though, dmd does produce useful information for this 
simple case:

Error: static assert  "Invalid string merhaba"
        instantiated from here: foo!("merhaba")

The only shortcoming that I see in this case is that the implementations 
for different string values are inside the same function template.

 > but duplicating same condition twice (one
 > time being part of implementation) hurts my eyes :(

Can you elaborate. I don't see the duplication.

Ali



More information about the Digitalmars-d-learn mailing list