C++11 Iterators and Lambdas (Revisited)

Last week I introduced an article where I tested C++11 support in Apple’s version of the clang compiler (Apple clang 4.0).

As you may remember, after conducting some tests, I was left with the impression that clang’s implementation was far behind of what I was expecting, with some notable features missing like initializer lists and some iterator constructs. This week I decided to revisit what had been done by studying the clang documentation.

After some reading, it turns out that C++11 support is beyond what I originally though. The problem is that (at this point) C++11 support is still an “opt-in” compiler option.

Language support is turned off by default and so is the standard library. That’s right, clang is shipping with not one but two C++ standard libraries: the C++ 2003 legacy library (libstdc++) and the new C++11 library (libc++). You need to tell clang that you want it to link against the new library, something I was not doing before!

With this in mind, let’s develop a new C++11 program:

Now, many things have changed since our last program. We can now access lots of goodies from the new standard, including (as noted in the code): initializer lists, std::for_each, std::begin, std::end, lambda expressions and the new “auto” keyword semantics. They are all supported and work as expected.

To build this program, assuming you’re using Apple’s clang 4.0 or the Open Source clang version >= 3.2, use the following command:

Notice how I explicitly invoke clang++ as opposed to clang and how I must specify the standard library version to use. libc++ is the LLVM’s project implementation of the new C++11 standard library.

If you have been following with your text editor and compiler, the output generated by running this program should be something like:

This now feels much better, much more in tune with what one would expect from a project as important as LLVM.

In my next article I will continue exploring C++11’s implementation in clang as I test more advanced features of the language such as shared pointers and threading. Stay tuned!