(Re)named std::pair members

前端 未结 9 1753
挽巷
挽巷 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:01

    Although not perfect, it is possible to use tagged data:

    template 
    typename tag_type::type& get(pair_type& p);
    
    typedef std::pair city;
    struct name { typedef std::string type; };
    struct zipcode { typedef int type; };
    
    template <>
    std::string& get(city& city)
    {
       return city.first;
    }
    
    template <>
    int& get(city& city)
    {
       return city.second;
    }
    
    int main()
    {
       city c("new york", 10001);
       std::string n = get(c);
       int z = get(c);
    }
    

    But as Ben Voigt says: struct city { string name; int zipcode; }; would pretty much always be better.

    EDIT: Templates probably are an overkill, you could use free functions in a namespace instead. This still does not solve type safety issues, as any std::pair are the same type as any other std::pair:

    namespace city
    {
       typedef std::pair type;
    
       std::string& name(type& city)
       {
          return city.first;
       }
    
       int& zipcode(type& city)
       {
          return city.second;
       }
    }
    
    int main()
    {
       city::type c("new york", 10001);
       std::string n = city::name(c);
       int z = city::zipcode(c);
    }
    

提交回复
热议问题