Why does std::pair expose member variables?

For the original C++03 std::pair, functions to access the members would serve no useful purpose.

As of C++11 and later (we’re now at C++17, with C++20 coming up fast) std::pair is a special case of std::tuple, where std::tuple can have any number of items. As such it makes sense to have a parameterized getter, since it would be impractical to invent and standardize an arbitrary number of item names. Thus you can use std::get also for a std::pair.

So, the reasons for the design are historical, that the current std::pair is the end result of an evolution towards more generality.


In other news:

regarding

As far as I know, it will be better if encapsulating two member variables above and give a getFirst(); and getSecond()

no, that’s rubbish.

That’s like saying a hammer is always better, whether you’re driving in nails, fastening with screws, or trimming a piece of wood. Especially in the last case a hammer is just not a useful tool. Hammers can be very useful, but that doesn’t mean that they’re “better” in general: that’s just nonsense.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)