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

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


On Sunday, 24 August 2025 at 08:25:56 UTC, H. S. Teoh wrote:
> On Sun, Aug 24, 2025 at 05:20:06AM +0000, David T. Oxygen via 
> Digitalmars-d-learn wrote: [...]
>> But I still don't know how to use `is` `__traits`.
> [...]
>
> Operations involving types, such as type comparisons, are 
> usually done only inside an `is`-expression.  For example:
>
> ```
> struct MyType { ... }	// concrete definition of type
> alias MyAlias = MyType;	// an alias to a type
>
> static assert(is(MyAlias == MyType));
> ```
>
> Usually this is most useful inside template functions that take 
> one or more types as compile-time arguments.  For example:
>
> ```
> void myFunc(T)(T data) {
> 	static if (is(T == string)) {
> 		writeln("data is a string");
> 		string x = data;
> 		// ... handle string data
> 	} else static if (is(T : double)) {
> 		writeln("data is not a string, but implicitly converts to 
> double");
> 		double d = data;
> 		// ... handle double data
> 	} else {
> 		static assert(0, "don't know how to handle type: " ~ 
> T.stringof);
> 	}
> }
> ```
>
> For more information, see:
>
> 	https://wiki.dlang.org/Is_expression
>
>
>> And, how can I fill in `/*?????*/`? Can I use 
>> `typeid(result)==MyInt`? Or if the `is` keyword can do this?
>
> You'd write this as:
>
> ```
> is(typeof(result) == MyInt)
> ```
>
> if the type must be exactly MyInt, or
>
> ```
> is(typeof(result) : MyInt)
> ```
>
> if the type may be something else that implicitly converts to 
> MyInt.
>
>
--
Thank you very much. But I made the `result` a `MyReal` object. 
And the `typeof` is a compile-time keyword. So can I get the 
expected answer at runtime? I'm afraid that `is(typeof(result) == 
MyInt)` will never be true.




More information about the Digitalmars-d-learn mailing list