(Re)named std::pair members

前端 未结 9 1777
挽巷
挽巷 2020-12-14 07:18

Instead of writing town->first I would like to write town->name. Inline named accessors (Renaming first and second of a map iterator and Name

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 08:03

    You can use pointer-to-member operators. There are a few alternatives. Here is the most straightforward.

    typedef std::map< zipcode_t, std::string > zipmap_t;
    static zipcode_t const (zipmap_t::value_type::*const zipcode)
                                                  = &zipmap_t::value_type::first;
    static std::string (zipmap_t::value_type::*const zipname)
                                                  = &zipmap_t::value_type::second;
    
    // Usage
    zipmap_t::value_type my_map_value;
    std::string &name = my_map_value.*zipname;
    

    You can put the accessors for one pseudo-type into a dedicated namespace to separate them from other things. Then it would look like my_map_value.*zip::name. But, unless you really need to use a pair, it's probably easier to just define a new struct.

提交回复
热议问题