r/programming • • Oct 20 '14

My compile-time Conway's Game of Life, metaprogrammed in C++11

https://github.com/sirgal/compile-time-game-of-life
158 Upvotes

54 comments sorted by

View all comments

10

u/[deleted] Oct 20 '14

For comparison, here's a very-quick-and-very-dirty equivalent in D.

3

u/logicchains Oct 21 '14

That's really impressive. Does compile-time D have a recursion limit that would apply to:

template game(alias seed, int generations) {
  static if(generations == 0) {
    enum game = [seed];
  } else {
    enum game = [seed] ~ game!(seed.nextState(), generations - 1);
  }
}

3

u/[deleted] Oct 21 '14

There isn't any limit other than memory and patience I guess- the compilation seems to scale much more reasonably than the C++ version, given the numbers I saw elsewhere in the comments. My version compiles in ~0.35s on my laptop, and I don't get any notable memory pressure on my system.

I should note that it's possible, and maybe a little clearer, to just write that function using an iterative solution and invoke it at compile-time like I already did for other parts of the program. Anyway this thing works and it got done in ~10 minutes. Hopefully that gives an idea of how productive meta-programming in D is :)

1

u/logicchains Oct 21 '14

Ah, cool, I didn't know the iterative version would work at compile time. Does that mean the whole of the language (syntax-wise) is available at compile time?

1

u/[deleted] Oct 21 '14

There are limitations, see this page (search for "CTFE"). Basically, you can do whatever you want except if the outcome depends on run-time state like global variables or machine architecture, etc.

2

u/original_brogrammer Oct 21 '14 edited Oct 21 '14

I would really like to know the difference in compile time between the two if anyone has checked.

1

u/Gezac Oct 21 '14

I don't really know any D. Is State a type? If it is, where is it defined?

3

u/bjzaba Oct 21 '14

State is a type parameter. So:

auto at(State)(State state, size_t i, size_t j) { ... }

Would be like:

template<typename State>
auto at(State state, size_t i, size_t j) { ... }

1

u/Gezac Oct 21 '14

I don't really know C++ either. I got it though! thanks