What's the use of 'typeof','typeid','__traits','is' ?

David T. Oxygen TKC847567 at outlook.com
Sun Aug 24 03:13:38 UTC 2025


Hello every kind and helpful D programmers, I need your help.

I've met two problems about getting types.
In D, we can use many keywords to get the type of an object, such 
as `typeof`,`typeid`,`is`.
However, I don't know the differences between them well. I also 
don't know how to use them in D...

And yesterday, I've met an actual problem. If I'm writing a math 
library(Actually I'm not, it's an example just like my case):
```d
class MyReal{
     //...
}

class MyInt:MyReal{
     public cent value;
     this(string makeNum){
         //...
     }
     MyReal opBinary(string op)(MyReal another){
         //...
     }
}

class MyFloat:NyReal{
     public double value;
     //...
}

```

The code above has simplified. It defines some simple classes.

And now, I have a function:
```d
import std.algorithm.searching;
MyReal is_int_or_float(string inputs){
     if(inputs.canFind('.'))
         return new MyFloat(inputs);
     else
         return new MyInt(inputs);
}

```

The `is_int_or_float()` function has also simplified.
Then I need to use another function to get the type of the result 
of `is_int_or_float()`, so I may write another piece of code like:
```d
import std.stdio;
string inputing="3.14";
MyReal result=is_int_or_float(inputing);
if(/*?????*/){
     writeln(cast(MyInt)result);
}else{
     writeln(cast(MyFloat)result);
}
```

Then I met the problem: I don't know to use which tool to get the 
type of `result`. I've tried many ways but it didn't help.
And strangely, I've met two cases like these code above 
yesterday, but sometimes one writing method could work well, but 
another couldn't. That made me surprised.

Can you solve the problem? What are the use of those keywords? 
How to use them? Which I should use to fill in the `/*?????*/` ? 
I'm waiting for you.



More information about the Digitalmars-d-learn mailing list