Categories
Coding

The Elements of Modern C++ Style

Herb Sutter has a fantastic short article over at his site on the new C++11 standard. The new extensions to the language are way overdue. One particular example that I really liked was the application of library algorithms and lambdas to create “extensions” to the language. For instance, the example below adds a “lock” construct (similar to the one in C#):

[sourcecode language=”cpp” wraplines=”true”]
// C#
lock( mut_x ) {
… use x …
}

// C++11 without lambdas: already nice, and more flexible (e.g., can use timeouts, other options)
{
lock_guard<mutex> hold { mut_x };
… use x …
}

// C++11 with lambdas, and a helper algorithm: C# syntax in C++
// Algorithm: template<typename T, typename F> void lock( T& t, F f ) { lock_guard<t> hold(t); f(); }
lock( mut_x, [&]{
… use x …
});
[/sourcecode]

Of course, all of this is dependent on compiler support. A couple of nice resources on the current state of C++11 support are:

http://www.aristeia.com/C++11/C++11FeatureAvailability.htm

and

https://wiki.apache.org/stdcxx/C%2B%2B0xCompilerSupport