(Re)named std::pair members

前端 未结 9 1754
挽巷
挽巷 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

    Probably not worth the extra memory, but if you want to retain the advantage of std::pair or std::tuple/ maintain compatibility with an unchangeable API, you can inherit from them and then define references to their members.

    Apart from the memory cost, this comes with the giant caveat that STL types generally don't have virtual destructors and can thus cause memory leaks if you attempt to de-allocate using a pointer to the base type:

    #include 
    
    struct PairShadow : public std::pair {
        using std::pair::pair;
        PairShadow & operator=(PairShadow const &) { /*call parent op here*/ }
        int & x = this->first;
        double & y = this->second;
    };
    
    struct TupleShadow: public std::tuple {
        using std::tuple::tuple;
        PairShadow & operator=(PairShadow const &) { /*call parent op here*/ }
        int & x = std::get<0>(*this);
        double & y = std::get<1>(*this);
    };
    
    auto main() -> int {
        auto twinShadow = PairShadow(1,3.0);
        auto tupleShadow = TupleShadow(1,3.0);
        return tupleShadow.y;
    }
    

    Alternatively, and perhaps preferrably as mentioned by @holyblackcat you could also just define an overload to std::get(PairShadow) for your struct in many cases as long as you aren't trying to conform to an unchangable API which specifically requires a std::pair or std::tuple

提交回复
热议问题