std::ignore – Elegant solution to a simple problem

If you love tuple (you probably do already), there’s a clever way to have clean code, similar to python, to pass parameters for which you don’t actually care to have the value to. To restate that, an easy way to extract only 1 or 2 of the values from a multi-value tuple and ignoring the rest. A common example is with inserting a value into a set. If you want to verify if a value is already in the set, a common idiom is to insert the value in the set, and verify the return value to determine if the value was in fact inserted. If the value was inserted, then the value wasn’t already in the set. Mystery solved. Note: I use a pair in this example instead of tuple. Same idea.

First, let’s look at a lengthier implementation without using std::ignore:

std::set<std::string> mySet;

// insert some values in the set...

// return type is a pair of < iterator, bool >
using SetRetType = 
   pair<std::set<std::string>::iterator, bool>;
	
SetRetType retVal = mySet.insert("Value");
if (retVal.second)
{
	// New value inserted, do something...
}
Continue readingstd::ignore – Elegant solution to a simple problem