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

H. S. Teoh hsteoh at qfbox.info
Sun Aug 24 08:25:56 UTC 2025


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.


T

-- 
Once bitten, twice cry...


More information about the Digitalmars-d-learn mailing list