Eponymous template with static if

H. S. Teoh hsteoh at qfbox.info
Tue Aug 15 10:54:52 UTC 2023


On Tue, Aug 15, 2023 at 10:25:56AM +0000, sighoya via Digitalmars-d wrote:
> On Monday, 14 August 2023 at 14:49:06 UTC, Paul Backus wrote:
[...]
> > ```d
> > template square(T)
> > if (is(T)) // <-- right here
> > {
> >     T square(T param) { return param*param; }
> > }
> > ```
> 
> Can you tell what `is(T)` is doing here?
> From the docs it seems to require `T` to be existing.
> However, I don't know what this exactly means, as T anyway have to exist.

`is(T)` is standard idiom for checking whether T is a valid type.

It's usually used with an expression to test whether some operation is
valid on a type, e.g.:

	auto myTemplateFunc(T)(T data)
		if (is(data++))	// make sure ++ is valid on T
	{
		return data++;
	}

	auto myTemplateFunc(T)(T data)
		if (is(data+0))	// make sure + int is valid on T
	{
		return data + 123;
	}


T

-- 
English is useful because it is a mess. Since English is a mess, it maps well onto the problem space, which is also a mess, which we call reality. Similarly, Perl was designed to be a mess, though in the nicest of all possible ways. -- Larry Wall


More information about the Digitalmars-d mailing list