CT aggregate computations

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Mar 30 11:59:43 PDT 2017


On Thu, Mar 30, 2017 at 06:21:43PM +0000, Enigma via Digitalmars-d-learn wrote:
> Is it possible to compute at compile time computations on a manifest
> constant that contains values(in a somewhat complex way, but that
> shouldn't matter)?

Yes, see below.


> I am using foreach and it seems to be done dynamically as I can step
> through the code for each value and see them change. This tells me it
> is not done at compile time like it should be.

If you want something done at compile time, you have to ask for it. The
usual way is to use something like `enum` that must be known at
compile-time to force the compiler to run the computation through CTFE.


> I might have something like
> 
> 
> import std.meta, std.algorithm, std.stdio;
> void main()
> {
> 	enum X = [1,2,3,4,5];
> 	int y = 0;	
> 	foreach(x; X) // or foreach(x; aliasSeqOf!X), both iterate over y at run
> time according to the debugger.
> 	   y = max(x, y);
> 	
> 	writeln(y);
> 		
> }

Here is how to do it:

	auto computeY(int[] data)
	{
		int y = 0;
		foreach (x; data)
			y = max(x,y);
		return y;
	}

	void main()
	{
		enum X = [1,2,3,4,5];
		enum y = computeY(X);	// N.B.: enum forces CTFE
		writeln(y);
	}


> But I want it to be effectively the same as
> 
> 
> import std.meta, std.algorithm, std.stdio;
> void main()
> {
> 	enum X = [1,2,3,4,5];
> 	int y = 5;	
> 	writeln(y);	
> }
> 
> so y is computed at compile time. I'd rather not having to create some
> complex templates to handle it, which I think could be done using
> template recursion.
[...]

You don't need template recursion unless you're doing something at the
AST level.  For most computations you want done at "compile-time", you
can just use CTFE.

Again, I see the term "compile-time" is misleading people. You may want
to read the following (it's still a draft, but what's there should
help clear things up):

	http://wiki.dlang.org/User:Quickfur/Compile-time_vs._compile-time


T

-- 
Caffeine underflow. Brain dumped.


More information about the Digitalmars-d-learn mailing list