What are good use-cases for tuples in C++11?

It is an easy way to return multiple values from a function;

std::tuple<int,int> fun();

The result values can be used elegantly as follows:

int a;
int b;
std::tie(a,b)=fun();

Well, imho, the most important part is generic code. Writing generic code that works on all kinds of structs is a lot harder than writing generics that work on tuples. For example, the std::tie function you mentioned yourself would be very nearly impossible to make for structs.

this allows you to do things like this:

  • Store function parameters for delayed execution (e.g. this question )
  • Return multiple parameters without cumbersome (un)packing with std::tie
  • Combine (not equal-typed) data sets (e.g. from parallel execution), it can be done as simply as std::tuple_cat.

The thing is, it does not stop with these uses, people can expand on this list and write generic functionality based on tuples that is much harder to do with structs. Who knows, maybe tomorrow someone finds a brilliant use for serialization purposes.


I think most use for tuples comes from std::tie:

bool MyStruct::operator<(MyStruct const &o) const
{
    return std::tie(a, b, c) < std::tie(o.a, o.b, o.c);
}

Along with many other examples in the answers here. I find this example to be the most commonly useful, however, as it saves a lot of effort from how it used to be in C++03.

Tags:

C++

Tuples

C++11