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
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
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