C++0x lambdas in GCC 4.5

Lambdas are coming in GCC 4.5. With this I’ve rid myself of the clamp hack. You can start using lambdas today by just grabbing a GCC snapshot:

svn co -q svn://gcc.gnu.org/svn/gcc/trunk
sudo aptitude build-dep gcc-4.4 # get prereqs
./configure --program-suffix=-4.5 --disable-libgcj \
sudo make install
# test it out
echo 'int main() { []{}; return 0; }' > /tmp/nop.cc
g++-4.5 -std=gnu++0x -o /tmp/nop{,.cc}

Here’s a simple program from my C++ sandbox showing off just a few of C++0x’s slew of new features:

#include <functional>
#include <iostream>
#include <string>
#include <thread>
#include <vector>

using namespace std;
int main() {
  // strongly typed enums
  // can specify underlying type
  enum class msg_type : uint8_t { hello, world };
  // initializer lists for easy init
  // no more `>>` misparsing
  const vector<pair<int, string>> xs =
    {{1, "hello"}, {3, "world"}};
  // standard classes for concurrency
  vector<thread> ts;
  // type inference with repurposed `auto`
  // no need for `vector<string>::const_iterator`
  for (auto x = xs.begin(); x != xs.end(); ++x) {
    // new function class
    // could also use `auto` here
    // here's a lambda that captures x by value
    function<void()> f = [=]{
      // new chrono class
      cout << x->second << endl;
  for (auto t = ts.begin(); t != ts.end(); ++t) {
  return 0;

Compile it with:

g++-4.5 -std=gnu++0x -pthread -o c++0x{,.cc}

Other features are coming down the pipe as well. Wikipedia has good high-level overviews of these and more.

Follow me on Twitter for stuff far more interesting than what I blog.

  • clmm8899
  • Thank you very much, I will definitely follow you on Twitter, because am actually very interested!

  • Chris

    Thanks for this.
    P.S. Your link to clamp hack is broken.

  • Thanks for the heads-up