Slashdot Mirror


Clang Plays Tetris -- Tetris As a C++ Template Metaprogram

New submitter mjvzb writes: Ever wish compiling was more fun? Well, I recently implemented Tetris as a C++ template metaprogram (code at Github). The game is played by recompiling its source, taking player input by compiler flag. The runtime program is only needed to print the game screen to the console and save the game state across compiler runs.

Implementing Tetris in templates is not as horrific as you may imagine, and I've put together a post covering the details. Once you get over the syntax, C++ metaprogramming is just like functional programming.

68 comments

  1. C++ metaprogramming is just like functional progra by Cassini2 · · Score: 0

    C++ metaprogramming is just like functional programming.

    Say what?

  2. proves the old maxim by Anonymous Coward · · Score: 2, Insightful

    About semi-complex programs ending up re-implementing aspects of lisp or smalltalk-- just less elegantly.
    I think you've done it!

  3. C++ is an abomination by Anonymous Coward · · Score: 0

    This is proof as to exactly why C++ is such an abomination. I prefer languages that encourage elegant designs.

    1. Re:C++ is an abomination by rubycodez · · Score: 1

      Bjarne Stroustrup and Lennart Poettering have a lot in common....

    2. Re:C++ is an abomination by Anonymous Coward · · Score: 0

      Programming languages can't prevent bad programmers.

  4. Re:C++ metaprogramming is just like functional pro by Anonymous Coward · · Score: 1

    Nonfunctional programming is not really a different paradigm.

  5. Re:Terrifying. by Anonymous Coward · · Score: 4, Insightful

    Who are you to judge that? Maybe he was lost in the depths of suicidal depression, and this project gave him a reason to drag himself out of it. Maybe an alien race will visit the earth and think that this is just so goddamn clever that there's no reason not to share their hyperdrive tech with us. Or whatever. But basically, fuck you and don't worry about what other people choose to do or not do.

  6. Re:C++ metaprogramming is just like functional pro by Anonymous Coward · · Score: 1

    He presumably means "just like" in the same sense as in the phrase, "Eating a high end steak dinner is just like having someone saw through your kneecaps with a circular saw".

  7. Syntax by phantomfive · · Score: 3, Interesting

    Once you get over the syntax, C++ metaprogramming is just like functional programming.

    No, the syntax is the entire thing wrong with C++ metaprogramming. It clearly wasn't designed for things like this. To clear up any doubt about the syntax, check out this file. In addition the inscrutable error messages (although those have improved over the past decade). If anyone likes template metaprogramming, I suggest they just use LISP.

    That said, this project is really cool. Nice hack mattbierner.

    --
    "First they came for the slanderers and i said nothing."
    1. Re:Syntax by Threni · · Score: 1

      "In addition the inscrutable error messages"

      Well, Stroustrup himself describes them as "appalling", and Concepts was supposed to clean some of this stuff up. Roll on c++17...

    2. Re:Syntax by Cafe+Alpha · · Score: 1

      It's also that C++ requires so many workarounds for template metaprogramming, so many help libraries, so many types, that writing, say template metaprogramming library that plays nice with Boost takes an infinitude of time and detail.

      Syntax isn't the majority of the problem. The rest of it is even worse.

    3. Re:Syntax by John+Allsup · · Score: 2

      I really wish people would get away from the character-by-character idea of program source, and rediscovered the Lisp idea that program is a data structure. In the case of what, say, C or C++ do, it would be nice to develop a means to construct things like functions and classes (with reading from traditional character based source files implemented as a thin parser layer in front of this), add them to a program, and then through things (in this data structure form) over to a compiler.
      Source files would then be more like scripts that drive the compiler infrastructure.
      (And this again isn't new, but was the sort of thing that was happening in the 70s and 80s before C++ happened). C++ can all too easily become a syntactic cocaine habit.

      --
      John_Chalisque
    4. Re:Syntax by Anonymous Coward · · Score: 0

      Any code will look bad if you put 4000 characters in a single line. Templates can be arbitrarily indented, and intermediate results can be stored by aliasing "using result = template-expression". There is no excuse for that code to exist as it is.

    5. Re:Syntax by phantomfive · · Score: 1

      Look at the raw code, it's not much better

      --
      "First they came for the slanderers and i said nothing."
  8. Re:C++ metaprogramming is just like functional pro by phantomfive · · Score: 4, Insightful

    metaprogramming is like functional programming in these senses:

    1) Uses lots of recusion
    2) Has no variables, only constants. Nothing is mutable.
    3) Has functions

    Because of 1 and 2, it helps to think in terms of functional programming if you want to do anything substantial.

    --
    "First they came for the slanderers and i said nothing."
  9. Re:Terrifying. by phantomfive · · Score: 4, Insightful

    If only the people who want to take on challenges like this put their skills to something actually useful....... There has GOT to be a better use of your knowledge and skills.

    Sometimes people do things for fun........not because they want to please internet critics.

    --
    "First they came for the slanderers and i said nothing."
  10. Re:Terrifying. by SirSlud · · Score: 2, Insightful

    I am mystified how people can read this and not realize it was just a little fun thing to do in his spare time. Or do you spend every waking minute of your life doing serious things with your knowledge and skills?

    --
    "Old man yells at systemd"
  11. Is it allowed? by MarioJE · · Score: 1

    I thought Tetris issued cease and desist letters for any implementation of its game, even if only for educational purposes.

    1. Re:Is it allowed? by tlolczyk · · Score: 0

      Does that include this?

  12. Re:Terrifying. by phantomfive · · Score: 1

    When people find skills they are jealous of, they often try to discourage it and cover it up with phrases like:

    * Don't you have a life?
    * What a nerd
    * You have too much time on your hands
    * There has GOT to be a better use of your knowledge and skills
    * There's something wrong with you

    Ignore those critics and do what you want anyway. Your life will be better for it.

    --
    "First they came for the slanderers and i said nothing."
  13. no by Anonymous Coward · · Score: 0

    No, I don't wish compiling were more "fun". Like taking out the trash, or pruning my rose bushes, I want compiling to be over and done with as soon as possible so that I can get on with solving problems.

    I especially don't want to have to BE a compiler writer, or try to divine the twisted mind of a compiler writer to solve problems. But that is exactly what you have to be, and how you have to think to use C++.

    Which is why I won't touch it with a 10 foot pole.

    Terrible language, desperately grasping for relevance in a world that passed it by long ago.

    If you want functional programming, USE A FUNCTIONAL PROGRAMMING LANGUAGE.

    1. Re:no by Anonymous Coward · · Score: 0

      USE A FUNCTIONAL PROGRAMMING LANGUAGE.

      What if I want to use a functional programming language, but none of them are fast enough, I want to dip into imperative programming when I need to, I want tight control of my memory utilization, AND I want the compiler to fix as much as my shit at compile-time so it doesn't have to do it at run time?

    2. Re:no by Anonymous Coward · · Score: 0

      If you want functional programming, USE A FUNCTIONAL PROGRAMMING LANGUAGE.

      So... use C++?

    3. Re:no by Rockoon · · Score: 1

      What if I want to use a functional programming language, but none of them are fast enough

      If Fortran isnt fast enough, C++ will only make it worse.

      --
      "His name was James Damore."
    4. Re:no by ardor · · Score: 1

      Hint:
      you do not have to write C++ like this.
      I use C++11 a lot. It is a very nice language, as long as you avoid abominations like these.
      One problem is that template metaprogramming quickly became "cool", so everybody started to overuse it (*cough* Boost.Spirit *cough*). The result is a barely manageable mess that produces huge binaries.

      But if used sparingly, combined with all the niceness C++11 brought us, it is really nice to develop with modern (!) C++, especially if you are working on rather low-level stuff like realtime media decoding&playback or video game engines. It shares this space with C though, and the C vs C++ flamewars are still raging on...

      --
      This sig does not contain any SCO code.
  14. Re:C++ metaprogramming is just like functional pro by __aaclcg7560 · · Score: 1

    When I had a $100 steak in Las Vegas, it melted like butter in my mouth. I don't think taking a circular saw to your kneecaps has the same pleasant experience.

  15. ...just like functional programming! by Tailhook · · Score: 1

    Oh goody. So it's no different than any other monadic polymorphized differential functor system utilizing monoidal categories and parameterized applicative type expressions.

    Whew. Lucky me. I was worried about finding something to do over the holiday weekend.

    --
    Maw! Fire up the karma burner!
  16. Re:Terrifying. by MightyMartian · · Score: 1

    This is the most terrifying and ridiculous thing I've seen in my entire life.

    No, the most terrifying and ridiculous thing would be if it was rewritten in JavaScript which outputted Java source that piped C# source that then, when compiled and executed, outputted as an x86 ASM program that produced a PHP script.

    --
    The world's burning. Moped Jesus spotted on I50. Details at 11.
  17. Re:C++ metaprogramming is just like functional pro by serviscope_minor · · Score: 3, Informative

    Say what?

    Template metaprogramming is exactly functional programming.

    Not only that, C++98 style was completely 100% pure with no mutabe state. You got recuursion and pattern matching (called [partial] specialisation). A class is essentially a function returning a type (well, multiple types) as internal typedefs. And as such functions are very much first class objects.

    C++11 added some local mutable state. constexpr functions can now be evaluated at compile time. Those yielding an int can be used as template arguments.

    --
    SJW n. One who posts facts.
  18. Stupid and bad coder. by tlolczyk · · Score: 1

    That just just it. I remember Alexander Alexandrescu talking about such stupidity on Usenet in the mid90's. The code without a doubt is complex. slow and resource hogging since you use the compiler as an interpreter. Just a way of wasting watts ( the power it takes the computer to run ). No serious professional programmer would even try to attempt such a thing and there is really no reason to. It also flies in the face of things that Stroustrup and Sutter have been saying at conferences like CppCon2014 to keep things simple. I also remember Scott meyer making a joke about someone noticing the template system being turing complete.

    1. Re:Stupid and bad coder. by Anonymous Coward · · Score: 2, Insightful

      Go fuck yourself. Really. If you don't realize that this is a toy and a very clever one at that, I'm not sure what to tell you. Sometimes some things are done to scratch an itch, or for fun or something. You can learn an awful lot about how to do things/not do things by playing around with projects like this. Oh right, you are a "serious professional programmer" with ZERO passion for the work you do.

      Also you seriously have zero sense of humor. You must be great fun at parties.

  19. Re:C++ metaprogramming is just like functional pro by tlolczyk · · Score: 1

    C++ TMP is turing complete and has no state. So yes it is functional. The point is not to write games though, but to write better tuned library code. I can only guess at the illicit substances the person doing this was ingesting.

  20. Re:Terrifying. by Anonymous Coward · · Score: 0

    If only the people who want to take on challenges like this put their skills to something actually useful....... There has GOT to be a better use of your knowledge and skills.

    Sometimes people do things for fun........not because they want to please internet critics.

    Then why would they blog about it... and then submit an article to Slashdot describing and linking to their own god dam blog.

    Ordinarily I would agree with you, but this Matt Bierner clown clearly wants the fame, so he should cop any criticism on the chin.

  21. Re:The code is garbage by Anonymous Coward · · Score: 1

    How complicated can you make a rube goldberg machine? That's what this is thing is, a hacker's rube goldberg machine. Stop being so serious dickwads.

  22. Re:C++ metaprogramming is just like functional pro by Anonymous Coward · · Score: 0

    This confused me so much, I concurrently shot in my shorts and threw up in my mouth.

  23. Re:C++ metaprogramming is just like functional pro by beelsebob · · Score: 2

    Has no variables, only constants. Nothing is mutable.

    And... this is the definition of functional programming (referential transparency). So yes - it actually really *just like* functional programming, because it *is* functional programming.

  24. Blink. Horrible. Really horrible. by Cafe+Alpha · · Score: 2

    I've done that sort of metaprogramming. Years ago I wrote a compile-time Lisp interpreter. It's a HORRIBLE language.

    Look, say you have some advanced feature. You could write a library in scheme - it will take you 1 day to a week.

    You could write it in C++ templates. It will have a worse feature set than the scheme version, it will be much less readable (not that scheme is readable) and much harder to use. It will have unusable error messages. And a mockup version will take you months to write.

    Getting your mockup embedded in Boost and working well with it will take the help of a bunch of experts and a two or three times as much work.

    If you want it included in the Boost libraries, you'll need a couple years of work integrating it and getting it approved.

    Horrible.

  25. One sad thing by Cafe+Alpha · · Score: 1

    someone was asking for the luajit implementer, Mike Pall, to add copying data structures as something optimized by the compiler and he was told that not sharing structures was a "code smell"

    Oh God. The implementer is so out of touch and focused on low level efficiency that he doesn't recognize the basics of reliable programming.

  26. Misplaced Mistrust by SuperKendall · · Score: 1

    Some time ago Elon Musk went on a rant about AI's destroying us.

    AI's I do not fear, but C++ templates... there he might have something.

    --
    "There is more worth loving than we have strength to love." - Brian Jay Stanley
    1. Re:Misplaced Mistrust by phantomfive · · Score: 1

      rotfl

      --
      "First they came for the slanderers and i said nothing."
  27. Re:Terrifying. by Cafe+Alpha · · Score: 1, Insightful

    Nonsense.

    No one should ever have to work with C++ metaprogramming in their work.

    It should not be encouraged. It's a horrible dead end. Sadly it isn't the only dead end in computer science.

  28. Am I The Only One Who Does Not Know? by Anonymous Coward · · Score: 0

    What the fuck is "metaprograming"?

    1. Re:Am I The Only One Who Does Not Know? by tlolczyk · · Score: 0

      Metaprogramming comes in two forms:metaprogramming, and metaobject programming.

      Metaobject programming is writing code that modifies the way objects act. A version of this is aspect-oriented programming (which you may have heard of), which is supposed to be safer. An example of this would be to modify the way methods are called. For example, you write to a file the name of a method and it's parameter when it's called. Something like that would be useful for writing test scripts.

      The best example of metaobject programming would be Ruby on Rails, where derfinition files are read and a program generates the objects that are represented in the database as well as the db tables, queries etc.

      Metaobject programming is considered very dangerous, because if a moron is using it he can rewrite object behavior to the point where you get some very unexpected behaviour.

      Metaprograming, is simply writing a program that writes programs.

      The simplest version of metaprograming are macros.

      An interesting and easily understood paper, "Aspecet-Oriented Programming Kiczales et al", he desceribes having a set of routines which manipulate images. Doing things like and-ing and xor-ing the images. The problem arises when you have to do a lot of these operations at once, it becomes very slow. The trick is that they wrote Lisp code which generated C code. When they wrote code composing multiple filters, the Lisp would analyse it and merge loops before generating the C code. In that way he was acle to significantly reduce runtime.

      Templates automatically generate code so are automatically metaprograming, but the term means something more general allowed mostly by specialization. Imagine some template class method Foo::bar which is implemented in some way, but that for the class Quick the usual way is slower then another way then you can write Foo::bar{faster way} and For::bar{standard way

      . When generating the template code,if the class is Quick it will called the specialized version otherwise it will call the standard technique. This allows recursion to terminate, So the template system happens to be a turing complete system. you can write programs with templates that are run during compile time. That is template metaprograming.

      Usally TMP is used to generate libraries that are more more efficient, smaller etc... , For example a very simple TMP is std::copy which simply copies objects, but the specialization std::copy will be specialized to call memcpy which can be much faster then the object copy.

  29. Could versus Should by BitZtream · · Score: 1

    Sometimes you have to ask yourself, just because I CAN do this ... SHOULD I do this?

    No.

    In this case, the answer is clearly no.

    --
    Persistent Volume manager for Kubernetes - https://github.com/dwimsey/openshift-pvmanager
  30. Really "C++ Plays Tetris", not Clang... by macshit · · Score: 2

    The title of this article is a little misleading, as this program works fine with the latest release of gcc (5.1) as well...

    [No changes, either to the program or the command-line are required, just use "g++" instead of "clang++".]

    Presumably it will also work with any compiler that supports a recent-enough version of the C++ standard and its proposed updates (with the command-line options updated accordingly).

    --
    We live, as we dream -- alone....
    1. Re:Really "C++ Plays Tetris", not Clang... by lott11 · · Score: 1

      This shows how much intellectual development some of you have today. I guess most of you would say that spending your time in front of TV is a hobby. Or time well spent is watching sports on the boob tube. This is what I would expect from a large majority of all the illustrious critics. It is a mind game. It is a way of expanding the elasticity of thought, or distraction from every days monotony. I think of 17 different ways that it can be use for. cryptography, matter displacement, sorting crystalline structures. Mathematical models in wave forms. Well to make it short it dose have applications other than a game. It can be used for scientific research. But them we are dealing with obtuse intellectuals! There is no point of viewing it any other way but there's. Well done mjvzb

    2. Re:Really "C++ Plays Tetris", not Clang... by Anonymous Coward · · Score: 0

      What the fuck comment are you replying to? Definitely not the OP of your thread...........

  31. Re:Terrifying. by ShanghaiBill · · Score: 3, Interesting

    This is the most terrifying and ridiculous thing I've seen in my entire life.

    Americans have spent more than a trillion hours watching reality TV. That is far more terrifying and ridiculous than someone playing with a Turing-complete compiler meta-language.

  32. Re:Terrifying. by ShanghaiBill · · Score: 2

    No one should ever have to work with C++ metaprogramming in their work.

    He wasn't working.
    He was playing.

  33. Re:Terrifying. by phantomfive · · Score: 3, Insightful

    Then why would they blog about it... and then submit an article to Slashdot describing and linking to their own god dam blog.

    Because other people like to see it, and it's really cool. Specifically, if you don't like this kind of thing, you shouldn't be on Slashdot. See also this.

    --
    "First they came for the slanderers and i said nothing."
  34. Re:Terrifying. by phantomfive · · Score: 1

    Wow, you must hate programming, if you think it's about work.

    --
    "First they came for the slanderers and i said nothing."
  35. Re:C++ metaprogramming is just like functional pro by Anonymous Coward · · Score: 0

    Template metaprogramming is exactly functional programming.

    I got enlightened when I realized that C++ template metaprogramming is actually writing Prolog with a funny syntax.

  36. Re:C++ metaprogramming is just like functional pro by Jane+Q.+Public · · Score: 1

    This is like "functional" programming about as much as playing hopscotch all the way to the next town is like taking the train.

  37. Re:Terrifying. by serviscope_minor · · Score: 1

    No one should ever have to work with C++ metaprogramming in their work.

    In your own words: nonsense.

    Like all tools it requires skill and good taste to use. You can do stupid stuff with it, but then there isn't a language out there which doesn't let you make stupid design decisions.

    --
    SJW n. One who posts facts.
  38. Re:Terrifying. by unixisc · · Score: 2

    This is the most terrifying and ridiculous thing I've seen in my entire life.

    If only the people who want to take on challenges like this put their skills to something actually useful....... There has GOT to be a better use of your knowledge and skills.

    It is one of the first things people do in programming - building games. My son is on the verge of learning computing, and he wishes to build a few games. Once these simpler things are achieved, more complex things are easier to do by more people.

  39. Re:Terrifying. by Anonymous Coward · · Score: 0

    The first thing I did in programming (on a Commodore 64) was building a database. Pretty sure it wasn't remotely game-like :)

  40. Re:Terrifying. by Anonymous Coward · · Score: 0

    Yeah they should do something useful! Like for instance:

    Come up with ways to spy on your fellow citizens

    Come up with ways to efficiently kill your fellow citizens

    Come up with ways to brainwash your fellow citizens into submission

    Come up with ways to make a couple of your fellow citizens an extraordinary amount of money in the hopes they might toss you some scraps

    There are all kinds of great jobs in the tech sector these days in america.

  41. Re:Terrifying. by Anonymous Coward · · Score: 0

    It's almost all template programming anyway, just at a lower level.

  42. Difference between programming and metaprogramming by Anonymous Coward · · Score: 0

    ... there really shouldn't be any.

    I think the whole template 'metaprogramming' mess can be implemented
    very well and readably by normal functions. After all, the only real difference
    is that stuff is (partially) evaluated at compile time.

    'template double power(double x)' would transform into:
    double power(double x, constexpr int N);

    'template void swap(T& x, T& y)' would become:
    void swap(/* any type */ &x, /* any type */&y) {
        assert_sametype(x, y);
        assert_moveable(x); // ...
    }

    etc.

    Expanding the idea, things that should logically be possible but are illegal with
    current template syntax become trivial, e.g. templatizing on non-integral constants.
    Even user-defined types become first-class citizens:

    template void f() becomes: void f(constexpr double x);

    struct Rectangle { int w; int h; };
    template void clip() -> void clip(constexpr Rectangle R);

    BTW, variables are over-rated, everything should be const unless specified
    otherwise (use mutable, for instance).

    I hope I can prove my point sometimes by designing that language,
    but I'd need time and money... :)

  43. Re: Terrifying. by loufoque · · Score: 1

    Metaprogramming is useful for real things. It allows to automate some code generation instead of weiting redundant code by hand, which is definitely a great thing.

  44. Re: Terrifying. by Cafe+Alpha · · Score: 1

    Metaprogramming is wonderful. C++ templates are horrible.

    "Captain, you're asking me to work with equipment which hardly very far ahead of stone knives and bearskins. " - Mr. Spock

  45. Re:Difference between programming and metaprogramm by Cafe+Alpha · · Score: 1

    I don't see why you can't have multistage compiling so that you can use the full power of (whatever language) at "compile" time.

    You should be able to have mutable data structures at compile time.

    You should be able to have tables and arrays.

    And custom file and network io.

    Security hole? Like running a bash script isn't a security hole.

  46. Re: Terrifying. by loufoque · · Score: 1

    Not any more horrible than any other pure functional programming language, and people tend to find those elegant more than horrible.

  47. Re: Terrifying. by Cafe+Alpha · · Score: 1

    Pure functional programming is pretty horrible too.

    Take the classic book, "numerical recipes in Fortran"
    ( http://apps.nrbook.com/fortran... ) and try to convert all of the routines in there to pure functional style with no mutable variables, structures, arrays and no non-recursive loops.

    Big step backwards. It will be horrible, it will obscure the code and it will run slowly.

    It's funny that computer science doesn't build on old successes. They had good computer languages for doing math going back to the 50s but the latest and greatest bullshit being pushed in academia can't even do what they did in the 50's well.

  48. Preprocessors are cool by allo · · Score: 1

    void foo(bool on) {
            if(on){
                #define FOO
            } else {
                #undef FOO
            }
    }