How to get the element type of an array?

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Aug 25 04:36:56 UTC 2020


On Tue, Aug 25, 2020 at 03:41:06AM +0000, Jon Degenhardt via Digitalmars-d-learn wrote:
> What's the best way to get the element type of an array at compile
> time?
> 
> Something like std.range.ElementType except that works on any array
> type.  There is std.traits.ForeachType, but it wasn't clear if that
> was the right thing.
[...]

	alias T = ... /* the type to inspect */
	static if (is(T : E[], E)) {
		... /* in this block, E is the element type */
	}

Or if you need to use it in another expression:

	template ArrayElemType(T) {
		static if (is(T : E[], E)) {
			alias ArrayElemType = E;
		}
		else
			alias ArrayElemType = void;
			// or static assert(0) if it should be an error
	}

	int[] myArr;
	pragma(msg, ArrayElemType!(typeof(myArr))); // int

	string myStr;
	pragma(msg, ArrayElemType!(typeof(myStr))); // immutable(char)


T

-- 
The best way to destroy a cause is to defend it poorly.


More information about the Digitalmars-d-learn mailing list