Using std::reference_wrapper as the key in a std::map

前端 未结 3 592
再見小時候
再見小時候 2021-01-12 01:18

I have a bunch of objects in a class hierarchy and would like to make a std::map using references to those objects as the keys in the map. Its seems like

3条回答
  •  被撕碎了的回忆
    2021-01-12 02:21

    By default std::map uses std::less> as Compare, but std::reference_wrapper doesn't forward operator<() to the underlying type T.

    The simplest and concisest option to solve your problem is to define std::less (or std::greater) in the map definition like this:

    std::map, int, std::less> table;
    

    It will work correctly and as expected due to implicit conversion of std::reference_wrapper to T& and implicit constructor of std::reference_wrapper.

    Example.

提交回复
热议问题