(Re)named std::pair members

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

    perhaps you can inherit your own pair class from pair and set two references called name and zipcode in your constructor ( just be sure to implement all constructors you will use )

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-14 08:05

    I came up with a Utility_pair macro that can be used like this:

    Utility_pair(ValidityDateRange,
        time_t, startDay,
        time_t, endDay
    );
    

    Then, whenever you need to access the fields of ValidityDateRange, you can do it like this:

    ValidityDateRange r = getTheRangeFromSomewhere();
    
    auto start = r.startDay(); // get the start day
    r.endDay() = aNewDay();    // set the end day
    r.startDay(aNewDay1())     // set the start and end day in one go.
     .endDay(aNewDay2());
    

    This is the implementation:

    #include <utility>
    
    #define Utility_pair_member_(pairName, ordinality, type, name)      \
        const type &name() const { return ordinality; }                 \
        type &name() { return ordinality; }                             \
        pairName &name(const type &m) { ordinality = m; return *this; } \
    /***/
    
    #define Utility_pair(pairName, firstMemberType, firstMemberName, secondMemberType, secondMemberName) \
        struct pairName: std::pair<firstMemberType, secondMemberType>  {                                 \
            Utility_pair_member_(pairName, first, firstMemberType, firstMemberName)                      \
            Utility_pair_member_(pairName, second, secondMemberType, secondMemberName)                   \
        }                                                                                                \
    /***/
    
    0 讨论(0)
提交回复
热议问题