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!

Posted in C++

Playing with C++11 (using Clang)

I have been following the new C++ standard for quite some time (even before it was named C++11), so I’m very glad to see support for it reaching mainstream compilers such as clang, g++ and Visual C++.

Although this article here provides a good comparison of the state of the C++11 implementation in these three compilers, I wanted to give Clang on OSX a spin to see for myself how much of the new standard is actually supported in “real life” today.

I tried writing a short program that tested different features. I wasn’t expecting everything to work but, I was surprised to learn that some features that I was giving for granted are not widely available yet in clang 3.2 nor 4.0 .

Here’s my test program. It stores the numbers from 0 to 99 in a vector and then prints them to the console.

#include <algorithm>
#include <iostream>
#include <vector>

int main(int argc, char* argv[])
	// Create and populate a container:
	const int n = 100;
	std::vector<float> v(n);
	for (auto i = 0; i < n; i++)
		v[i] = i;
	// Iterate over v, applying a lambda expression on
	// each element.
	std::for_each(v.begin(), v.end(), [](int f) {
				std::cout << f << " ";

	std::cout << std::endl;

	return 0;

Some new C++11 features used in this program are:

  1. New std::for_each for iterating over a vector.
  2. New "auto" keyword semantics.
  3. Lambda Expressions (used here for printing elements).

Some features I wanted to try but are not yet supported in Clang 3.2, nor in Apple's Clang 4.0 are:

  1. Initializer Lists. Some people claim it is still not to be supported by Apple, but I couldn't get it to work on an open source build of Clang. Granted, I used 3.2. I should try building a newer clang perhaps even from trunk.
  2. std::begin() and std::end(), which should come with the updated Standard Library. It seems the STL implementation is not complete yet.

If I have time to try different compiler configurations, I might post the results here. All in all I'm happy with support reaching the mainstream and hope that I can start writing C++11 code in my next assignment.

Posted in C++

Dynamic Method Injection (in Objective-C)

When asked what I like the most from the Objective-C programming language, I often refer to its dynamic underpinnings.

Although Objective-C is a superset of C, the way its designers decided to implement the Object model was dynamic. This provides a strong contrast with C++, which, although a superset of C as well, is a static-typed language.

In this post I will show how you can use the Objective-C runtime to dynamically add a method to an (Objective-C) class at runtime.

Let’s start by creating a Dummy class that has no methods whatsoever. I will put everything in the same file for the sake of simplicity, but in real-life code, you’d want to have separate files for the interface and the implementation.

#import <Foundation/Foundation.h>

@interface Dummy : NSObject

@implementation Dummy

Now, let’s implement a method to be dynamically added to Dummy. Interestingly enough, methods to add need to be implemented as C functions.

Here’s our implementation:

void newMethod(id self, SEL _cmd)
  printf("Hello from a dynamically added method! (self=%p)\n", self);

Now, let’s go to the main function and see how we can inject “newMethod” into the Dummy class. We will need to import the Objective-C runtime.

#import <objc/runtime.h>

int main(int argc, char* argv[])
  NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  // Add method to Dummy class (args explained below)
  class_addMethod([Dummy class], @selector(printHello), (IMP)newMethod, "v@:");
  Dummy* instance = [[Dummy alloc] init];
  [instance printHello];
  [instance release];
  [pool release];
  return 0;

When running this program, an output similar to this will be produced:

Hello from a dynamically added method! (self=0x10ad143a0)

So, let’s see how the method was added.

The heavylifting here is done by the class_addMethod function. This function, coming from the Objective-C runtime, allows you to register a new method in a class.

This feat requires a pointer to the function that implements the method (“newMethod”), but lets you assign any name you want to it (I chose “printHello”). Notice that’s the message I send to the Dummy instance.

The strangest parameter is perhaps the last “v@:”. This is actually a code for the argument types received by the “newMethod” function. All valid type codes can be found in the Apple reference, but to make things easier, “v@:” means that the function returns void (v) and receives an Object and a selector.