I’d like to think that I know a fair amount about C++, but I keep discovering new things on a weekly or daily basis. One of my recent sources of new information is the presentations from CppCon 2014. And the most recent presentation I’ve looked at is Herb Sutter’s Back to the Basics: Essentials of Modern C++ Style.

In the presentation, Herb mentions a feature of tuple that enables returning multiple values from a function. Of course, one can already return a pair<T1, T2> of values, but accessing the fields of a pair is suboptimal and not very readable:

pair<...> p = f(...); if (p.second) { // do something with p.first }

The designers of tuple must have listened, because of the function std::tie , which lets you destructure a tuple :

typename container::iterator position; bool already_existed; std::tie(position, already_existed) = mMap.insert(...);

It’s not quite as convenient as destructuring multiple values in other languages, since you need to declare the variables prior to std::tie ‘ing them, but at least you can assign them sensible names. And since pair implicitly converts to tuple , you can use tie with functions in the standard library that return pair s, like the insertion functions of associative containers.

Sadly, we’re somewhat limited in our ability to use shiny new concepts from the standard library because of our C++ standard library situation on Android (we use stlport there, and it doesn’t feature useful things like <tuple> , <function> , or <thread_local> . We could, of course, polyfill some of these (and other) headers, and indeed we’ve done some of that in MFBT already. But using our own implementations limits our ability to share code with other projects, and it also takes up time to produce the polyfills and make them appropriately high quality. I’ve seen several people complain about this, and I think it’s something I’d like to fix in the next several months.

Tags: c++