Return empty std::pair from function

user195488 picture user195488 · Aug 3, 2012 · Viewed 15.1k times · Source

Is it possible to return an empty pair from a function? Meaning, follow the rules of the function prototype, but do not have any elements in the pair (e.g. NULL). Understanding that a pair simply exists so I don't know if this is conceptually possible. I have a need to return a pair that is NULL or empty, if that makes any sense.

For example,

pair<int, int> MyClass::someFunction()
{

   // do something that means we need to return an empty pair
   return NULL; // <--- this does not work obviously
}

Unfortunately, boost is not a possibility for me.

Answer

Grizzly picture Grizzly · Aug 3, 2012

Generally speaking an empty pair doesn't even make sense. Afterall a pair is per definition a container containing two objects.

You could however make something like an empty pair using Boost.Optional. Then you would either use a boost::optional<std::pair<...>> giving you the option of returning either a pair or an empty state or use std::pair<boost::optional<...>, boost::optional<...>> for a pair where either object could be empty.