Named std::pair members
Hi all.
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.
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 ... ?
br,
Martin
[code]
#include <map>
#include <string>
#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;
city_t get_city(std::string const& name)
{
city_collection dummy;
if(dummy.find(name) != dummy.end())
return *dummy.find(name);
else
throw std::exception();
}
int main(int argc, char* argv[])
{
city_t a;
city_t b("Foo", 12345);
city_t c(b);
a.name;
a.pcode;
city_t x = get_city("?");
return 0;
}
[/code]
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]