How to check if an array is a manifest constant?

simendsjo simen.endsjo at pandavre.com
Sun Apr 3 08:29:32 PDT 2011


The behavior for manifest constant arrays is different from regular arrays and const/immutable
arrays. The problem is that typeof() returns T[]. How can I see if the array is a manifest
constant?


	void g(int[] x) { }

	const c = [1,2,3];
	static assert(is(typeof(c) == const(int[])));
	// cannot convert const(int[]) to int[]
	static assert(!__traits(compiles, g(c)));
	auto carr = c;
	static assert(is(typeof(carr) == const(int[])));
	assert(carr.ptr == c.ptr); // referenced

	immutable i = [1,2,3];
	static assert(is(typeof(i) == immutable(int[])));
	// cannot convert immutable(int[]) to int[]
	static assert(!__traits(compiles, g(i)));
	auto iarr = i;
	static assert(is(typeof(iarr) == immutable(int[])));
	assert(iarr.ptr == i.ptr); // referenced

	enum e = [1,2,3];
	// e is reported as int[] even if it's an enum
	static assert(is(typeof(e) == int[]));
	//static assert(is(typeof(e) == enum)); // not an enum (as expected)
	// it can be passed to funtions taking dynamic arrays
	void f(int[] x) {
		assert(e.ptr != x.ptr); // then the content is copied
	}
	f(e);
	// the behavior is different from other assignments
	// as the content is copied
	auto earr = e;
	assert(earr.ptr != e.ptr); // content is copied


More information about the Digitalmars-d-learn mailing list