Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::pair<A,B> not the same as std::tuple<A,B>? (Is there really no way?)

Why is std::pair<A,B> not the same as std::tuple<A,B>? It always felt strange to not be able to just substitute one with the other. They are somewhat convertible, but there are limitations.

I know that std::pair<A,B> is required to have the two data members A first and B second, so it can't be just a type alias of std::tuple<A,B>. But my intuition says that we could specialize std::tuple<A,B>, that is a tuple with exactly two elements, to equal the definition of what the standard requires a std::pair to be. And then alias this to std::pair.

I guess this wouldn't be possible as it is too straight-forward to not to be already thought of, yet it wasn't done in g++'s libstdc++ for example (I didn't look at the source code of other libraries). What would the problem of this definition be? Is it "just" that it would break the standard library's binary compatibility?

like image 878
leemes Avatar asked Feb 11 '16 23:02

leemes


People also ask

What is the difference between tuple and pair?

The Tuple is an object capable to hold a collection of elements, where each element can be of different types. The pair can make a set of two values, which may be of different types. The pair is basically a special type of tuple, where only two values are allowed.

Is std :: pair a tuple?

A tuple is an object capable to hold a collection of elements where each element can be of a different type. The class template needs the header <tuple> . std::tuple is a generalization of std::pair. You can convert between tuples with two elements and pairs.

What is an std :: pair?

std::pair is a class template that provides a way to store two heterogeneous objects as a single unit. A pair is a specific case of a std::tuple with two elements.

Are tuples faster than pairs?

It is fully expected that std::tuple will be slower than std::pair when not optimized, because it is more complicated object.


2 Answers

You've gotta be careful about things like SFINAE and overloading. For example, the code below is currently well-formed but you would make it illegal:

void f(std::pair<int, int>);
void f(std::tuple<int, int>);

Currently, I can disambiguate between pair and tuple through overload resolution, SFINAE, template specialization, etc. These tools would all become incapable of telling them apart if you make them the same thing. This would break existing code.

There might have been an opportunity to introduce it as part of C++11, but there certainly isn't now.

like image 50
Puppy Avatar answered Oct 12 '22 16:10

Puppy


This is purely historical. std::pair exist since C++98 whereas tuple came after and was initially not part of the standard.

Backward compatibility is the biggest burden for C++ evolution, preventing some nice things to be done easily !

like image 39
Colin Pitrat Avatar answered Oct 12 '22 15:10

Colin Pitrat