Re: Named std::pair members
On Oct 22, 5:31 am, "Martin T." <0xCDCDC...@gmx.at> wrote:
I recently stumbled over a discussion that asserted that code using
std::pair<string, int> instead of, say, struct city_t { string name;
int pcode; }; is hard to read as every time we access the pair we just
work with first and second and the user does not immediately see what
first and second should be.
Makes perfect sense. town->name tells me more than town->first.
What do you think of the following solution where std::pair is extended
via a preprocessor macro to contain two arbitrarily named member
references in addition to first and second ... ?
#define NAMED_PAIR_TYPE(TNAME, NAMED_FIRST, NAMED_SECOND) \
template<typename T1, typename T2> \
struct TNAME : public std::pair<T1, T2> \
{ \
TNAME() \
: pair() \
, NAMED_FIRST(first) \
, NAMED_SECOND(second) \
{ \
} \
\
TNAME(T1 const& val1, T2 const& val2) \
: pair(val1, val2) \
, NAMED_FIRST(first) \
, NAMED_SECOND(second) \
{ \
} \
\
template<typename OTHER1, typename OTHER2> \
TNAME(pair<OTHER1, OTHER2> const& r) \
: pair(r) \
, NAMED_FIRST(first) \
, NAMED_SECOND(second) \
{ \
} \
\
/* first, second aliases:*/ \
T1 & NAMED_FIRST; \
T2 & NAMED_SECOND; \} \
/*;*/
NAMED_PAIR_TYPE(named_city_t, name, pcode);
typedef named_city_t<std::string, unsigned int> city_t;
typedef std::map<city_t::first_type, city_t::second_type> city_collection;
[]
It looks wasteful because you add two data members (references) just
to name the same thing differently.
I would rather add a couple of (inline) accessor functions:
typedef std::pair<std::string, unsigned int> city_t;
inline std::string& get_name(city_t& c) { return c.first; }
inline unsigned int& get_pcode(city_t& c) { return c.second; }
and than:
citi_t city;
std::string& name = get_name(city);
--
Max
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]