Why does std::pair expose member variables?

后端 未结 7 1551
孤独总比滥情好
孤独总比滥情好 2021-02-03 17:37

From http://www.cplusplus.com/reference/utility/pair/, we know that std::pair has two member variables, first and second.

Why did

7条回答
  •  伪装坚强ぢ
    2021-02-03 17:47

    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++14, with C++17 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.

提交回复
热议问题