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:

#include <vector>
using std::vector;

#include <algorithm>
using std::for_each;

#include <iterator>
using std::begin;
using std::end;

#include <iostream>
using std::cout;
using std::endl;

int main(int argc, char* argv[])
{
	// Initializer List goodness : )
	vector<float> v = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f };

	// for_each loop Goodness using new iterators and a lambda:
	for_each(begin(v), end(v), [](float f) { cout << f << " "; });
	cout << endl;

	// New "auto" keyword semantics:
	auto f = v[v.size()-1];
	cout << "An element: " << f << endl;

	return 0;
}

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:

$ clang++ -std=c++11 -stdlib=libc++ main.cpp

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:

$ ./a.out
0 1 2 3 4 
An element: 4

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!