Saturday, March 21, 2015

Printing out C++11 Tuples

Hello, today I want to talk about displaying the values of a Tuple in C++11.

For a brief summary, a Tuple is a template class that allows an user to define a fixed-size collection of values and is a convenient way to pass some temporary data around in an organized way without having to declare a whole new struct or class.

So in my program, I wanted to print out my tuple variable in the console to verify the code is doing what I expect it to do.  But I also want to print it in a readable form such that it'll look something like { value1, value2, value3, ... }.  The simplest thing I can do is to just print it out right and there with something like the following :





This gets the job done but what if I want to print multiple tuples from different functions ? I don't really want to litter my code base with all these hard coded prints.  It would be nice to just call a Print function of some sort and pass in the tuple as a parameter.  To achieve this, we can do the following:


Let's discuss what's going on here.


This struct is essentially a tag that lets us know which index of the tuple we're looking at.  This way, the program can determine that if it's on the last iteration, it can format the string differently.


These three functions print the elements inside the tuple.  Notice that the second parameter of our template functions uses the empty struct that I've defined. Also notice that the second and third function has a hard coded tupleCount.  For the case of the hard coded 1, I am saying that if there's only 1 element remaining to print, print it and don't add a comma to the end of it.  For the case of the hard coded 0, this means the tuple is empty and so I print out a string to help identify that we passed an empty tuple into the print function.   The core of the complexity comes from the top function where tupleCount is actually variable.  Here, I'm using the concept of recursion to do the work.  First, we print out the element that the variable Count is telling us to print. Then we recursively call print and reducing the count by 1 each time.


Finally, this function here wraps the tuple elements with the brackets and provide an interface for us to call to print a tuple.

No comments:

Post a Comment