Compiler complaining about code that can't be reached, builtin types .equals()

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 25 11:43:30 PDT 2015


On 06/25/2015 11:26 AM, Sean Grimes wrote:

 >       /*
 >        * isBuiltIn() checks against all the builtin types in D
 >        * returns true if value instantiated as int, double,
 > immutable(char)[] etc...
 >        * returns false iff value is a user defined object
 >        */
 >      if(!isBuiltIn(value)){
 >          foreach(val; values){
 >              if(val.equals(value))
 >              return true;
 >          }
 >      }

That is a run-time conditional. There is no guarantee for the compiler 
that isBuiltIn() will return 'true' for every 'value'. For example, it 
can return 'false' for 42 but 'true' for 43.

To enable or disable code sections you can use 'static if'. However, 
isBuiltIn must be evaluable at compile time as well. Since isBuiltIn 
works with values (not types) in your case, you can't pass it to 'static 
if':

     static if (!isBuiltIn(value)) {  // <-- compilation error

You want isBuiltIn to be a template which works on a type (V in your case).

Here is a short example which treats 'int' and 'double' as built-in only:

import std.typetuple;

bool isBuiltIn(T)()
{
     foreach (T2; TypeTuple!(int, double/*, ... */)) {
         if (is (T2 == T)) {
             return true;
         }
     }

     return false;
}

struct S(V)
{
     void foo(V v)
     {
         static if (!isBuiltIn!V) {
             /* Assumes that non-built-ins support bar(). */
             v.bar();
         }
     }
}

void main()
{
     auto s = S!int();
     s.foo(42);
}

Ali



More information about the Digitalmars-d-learn mailing list