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:
- New std::for_each for iterating over a vector.
- New "auto" keyword semantics.
- 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:
- 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.
- 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.