Difference between std::pair and std::tuple with only two members?
Is there a difference between an std::pair
and an std::tuple
with only two members? (Besides the obvious that std::pair
requires two and only two members and tuple
may have more or less...)
Solution 1:
There are some differences:
-
std::tuple
is not required by the standard to ever be standard-layout. Everystd::pair<T, Y>
is standard-layout if bothT
andY
are standard-layout. -
It's a bit easier to get the contents of a
pair
than atuple
. You have to use a function call in thetuple
case, while thepair
case is just a member field.
But that's about it.
Solution 2:
An std::tuple
's name is longer (one extra character). More of those characters are typed with the right hand, so easier for most people to type.
That said, std::pair
can only have two values - not zero, one, three or more. TWO values. A tuple, however, has almost no semantic limitation on the number of values. An std::pair
, therefore, is a more accurate, type safe type to use if you actually want to specify a pair of values.