Quantcast
Viewing all articles
Browse latest Browse all 10

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.


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 10

Trending Articles