Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literate Coding Vs. std::pair, solutions?

As most programmers I admire and try to follow the principles of Literate programming, but in C++ I routinely find myself using std::pair, for a gazillion common tasks. But std::pair is, IMHO, a vile enemy of literate programming...

My point is when I come back to code I've written a day or two ago, and I see manipulations of a std::pair (typically as an iterator) I wonder to myself "what did iter->first and iter->second mean???".

I'm guessing others have the same doubts when looking at their std::pair code, so I was wondering, has anyone come up with some good solutions to recover literacy when using std::pair?

like image 295
Robert Gould Avatar asked Jun 25 '09 05:06

Robert Gould


2 Answers

std::pair is a good way to make a "local" and essentially anonymous type with essentially anonymous columns; if you're using a certain pair over so large a lexical space that you need to name the type and columns, I'd use a plain struct instead.

like image 146
Alex Martelli Avatar answered Oct 11 '22 21:10

Alex Martelli


How about this:

struct MyPair : public std::pair < int, std::string >
{
    const int& keyInt() { return first; }
    void keyInt( const int& keyInt ) { first = keyInt; }
    const std::string& valueString() { return second; }
    void valueString( const std::string& valueString ) { second = valueString; }
};

It's a bit verbose, however using this in your code might make things a little easier to read, eg:

std::vector < MyPair > listPairs;

std::vector < MyPair >::iterator iterPair( listPairs.begin() );
if ( iterPair->keyInt() == 123 )
    iterPair->valueString( "hello" );

Other than this, I can't see any silver bullet that's going to make things much clearer.

like image 35
Alan Avatar answered Oct 11 '22 21:10

Alan