C++ tuples, a quick overview


Ok, c++ tuples, here is quick and dirty:

// g++ 4.1
#include <string>
#include <iostream>
#include <tr1/tuple>
using std::tr1::tuple;
using std::tr1::tie;
using std::tr1::make_tuple;

tuple<std::string,int> parse_url(const std::string& url){
    return make_tuple("127.0.0.1",9000); //Cheat for parsing
}
int main(){
    std::string host;
    int port;
    tie(host,port) = parse_url("127.0.0.1:9000");
    std::cout << "Host: "<<host<< ":"<<port<<"\n";
}

At the first look, returning several values from a function/method in C++ may look awkward and contrary to the C++ way, being more usual in languages like python or perl.
However the fact is that template metaprogramming gives us the ability to do such good tricks and renders the rest for us in compile-time. This tuple templates are part of the TR1 and thats why we need to include them from <tr1/tuple> and use them from std::tr1 namespace, but they’ll be part of the next standard c++0x.

The logic behind the metaprogramming is simple, by the time you compile a tuple the compiler knows perfectly the size of the new type because you supply the template parameters.

tie() for example is a template that gets the given parameters and put references to them in an lvalue obj that can be assigned to, so its a painless way of getting results from a tuple_returning method.
make_tuple() goes the same way but creates a new tuple with copies of the provided parameters, so it is a quick way of creating tuples of any size, its like the current make_pair() but for tuples.

One Response to C++ tuples, a quick overview

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: