Named std::pair members

  • Permalink
  • submit to reddit
  • Email
  • Follow


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

0
Reply Martin 10/21/2008 10:31:34 PM

See related articles to this posting

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

0
Reply Maxim 10/22/2008 9:52:54 PM

Martin T. ha scritto:
> 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 ... ?

It's quite bad, IMHO. There are several drawbacks with this approach:

1) although the C++ standard says that references might not require
storage, in most implementation reference members increase the size of a
class by the size of a pointer. In you case you have to multiply by two
  (that is 8 bytes on a lot of platforms). Frankly 8 bytes per element is
*a lot* for a simple readability improvement.

2) in case none of the two member types is const, pair<> is assignable,
but your type is not, because references forbids the declaration of the
implicit assignment operator (see 12.8/12). In the non-const/non-const
case (and only that case) you should provide an explicit assignment
operator.

3) this use of references can be used to circumvent const-correctness:

   NAMED_PAIR_TYPE(named_city_t, name, pcode);
   typedef named_city_t<std::string, unsigned int>  city_t;
   const city_t city("Segrate", 20090);
   city.name = "Vimodrone"; // Ops! Modifying a const object!

> 
> <snip>
> 
> city_t get_city(std::string const& name)
> {
>     city_collection dummy;
> 
>     if(dummy.find(name) != dummy.end())
>         return *dummy.find(name);

Of course, you realize that dummy is always empty with this code...

This is very inefficient, for two reasons:

1) You should cache the result of the first call:

   city_collection::iterator it = dummy.find(name);
   if (it != dummy.end())
     return *it;

2) the return statement makes a copy of returned object

Moreover, while the map has immutable keys (you can't change the "first"
in elements of maps, because it has an added "const"), the returned
value has a non-const "city" member. This can be misleading.

A better idiom, in my opinion, is the following:

typedef std::map<std::string, int>  city_collection;
typedef city_collection::value_type city_t;

// you can wrap these in a macro if you want:
inline const std::string& city(const city_t& p) { return p.first; }
inline int& pcode(city_t& p)                    { return p.second; }
inline const int& pcode(const city_t& p)        { return p.second; }

int main(int argc, char* argv[])
{
     city_t b("Milano", 20100);
     city_t c(b);

     name(b);
     pcode(b);

     return 0;
}

Just my opinion,

Ganesh

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Alberto 10/22/2008 10:18:05 PM

Alberto Ganesh Barbati wrote:
> Martin T. ha scritto:
>> 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 ... ?
> 
> It's quite bad, IMHO. There are several drawbacks with this approach:
> 
> 1) although the C++ standard says that references might not require
> storage, in most implementation reference members increase the size of a
> class by the size of a pointer. In you case you have to multiply by two
>   (that is 8 bytes on a lot of platforms). Frankly 8 bytes per element is
> *a lot* for a simple readability improvement.
> 

I agree with you and Maxim that the reference approach isn't that good.
The one using accessor functions seems better.

> 2) in case none of the two member types is const, pair<> is assignable,
> but your type is not, because references forbids the declaration of the
> implicit assignment operator (see 12.8/12). In the non-const/non-const
> case (and only that case) you should provide an explicit assignment
> operator.
> 

OK. Something new for me. Never stumbled over this up to now ...
probably because adding reference members is not exactly a day-to-day
thing :)

> 3) this use of references can be used to circumvent const-correctness:
> 
>    NAMED_PAIR_TYPE(named_city_t, name, pcode);
>    typedef named_city_t<std::string, unsigned int>  city_t;
>    const city_t city("Segrate", 20090);
>    city.name = "Vimodrone"; // Ops! Modifying a const object!
> 

Ouch!! Didn't know that. With pointers it's kinda more obvious.

>> <snip>
>>
>> city_t get_city(std::string const& name)
>> {
>>     city_collection dummy;
>>
>>     if(dummy.find(name) != dummy.end())
>>         return *dummy.find(name);
> 
> Of course, you realize that dummy is always empty with this code...

Just was to test that it compiles.

> 
> A better idiom, in my opinion, is the following:
> 
> typedef std::map<std::string, int>  city_collection;
> typedef city_collection::value_type city_t;
> 
> // you can wrap these in a macro if you want:
> inline const std::string& city(const city_t& p) { return p.first; }
> inline int& pcode(city_t& p)                    { return p.second; }
> inline const int& pcode(const city_t& p)        { return p.second; }
> 

Hmmm ... Both you and Maxim used the free function approach for access.
Personally I much prefer the member-function approach as that can IMHO
help greatly with auto completion / "Intellisense" features.
And it's basically equivalent, or is it?

Here's a modified version:
[code]
#define NAMED_PAIR_TYPE(TNAME, NAMED_FIRST, NAMED_SECOND)  \
template<typename T1, typename T2>                         \
struct TNAME : public std::pair<T1, T2>                    \
{                                                          \
	TNAME() : pair() {}                                      \
	                                                         \
	TNAME(T1 const& val1, T2 const& val2)                    \
	: pair(val1, val2)                                       \
	{ }                                                      \
	                                                         \
	template<typename OTHER1, typename OTHER2>               \
	TNAME(pair<OTHER1, OTHER2> const& r)                     \
	: pair(r)                                                \
	{ }                                                      \
	                                                         \
	/* first, second aliases:*/                              \
	inline T1 const& NAMED_FIRST() const {return first;}     \
	inline T2 const& NAMED_SECOND() const {return second;}   \
	inline T1 & NAMED_FIRST() {return first;}                \
	inline T2 & NAMED_SECOND() {return second;}              \
}                                                          \
/*;*/
[/code]
cheers,
Martin


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Martin 10/23/2008 6:48:05 AM

On 22 oct, 06:31, "Martin T." <0xCDCDC...@gmx.at> wrote:
> 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 ... ?

I think you should look into Boost.Fusion.


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Mathias 10/24/2008 4:31:37 PM

On Oct 23, 1:48 pm, "Martin T." <0xCDCDC...@gmx.at> wrote:
> Alberto Ganesh Barbati wrote:
> > Martin T. ha scritto:
> >> 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.

[]

> Hmmm ... Both you and Maxim used the free function approach for access.
> Personally I much prefer the member-function approach as that can IMHO
> help greatly with auto completion / "Intellisense" features.
> And it's basically equivalent, or is it?
>
> Here's a modified version:
> [code]
> #define NAMED_PAIR_TYPE(TNAME, NAMED_FIRST, NAMED_SECOND)  \
> template<typename T1, typename T2>                         \
> struct TNAME : public std::pair<T1, T2>                    \
> {                                                          \
>         TNAME() : pair() {}                                      \
>                                                                  \
>         TNAME(T1 const& val1, T2 const& val2)                    \
>         : pair(val1, val2)                                       \
>         { }                                                      \
>                                                                  \
>         template<typename OTHER1, typename OTHER2>               \
>         TNAME(pair<OTHER1, OTHER2> const& r)                     \
>         : pair(r)                                                \
>         { }                                                      \
>                                                                  \
>         /* first, second aliases:*/                              \
>         inline T1 const& NAMED_FIRST() const {return first;}     \
>         inline T2 const& NAMED_SECOND() const {return second;}   \
>         inline T1 & NAMED_FIRST() {return first;}                \
>         inline T2 & NAMED_SECOND() {return second;}              \}                                                          \
>
> /*;*/
> [/code]

At this point it seems to be much simpler just to declare:

     struct city_t { string name; int pcode; };

as you mentioned in your original post and dispense with unnecessary
macro awkwardness.

Is there a reason why you would still like to use std::pair<>?

-- 
Max


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Maxim 10/24/2008 4:31:45 PM

I have seen people doing this:

#include "boost/tuple/tuple.hpp"
#include <string>

int main(int argc, char* argv[])
{
   enum { name, pcode };
   boost::tuples::tuple<std::string, int> np;

   np.get<name>() = "Olso";
   np.get<pcode>() = 12345;

   int n = np.get<pcode>();
   std::string s = np.get<name>();

   return 0;
}

Regards,
eca

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply eca 10/24/2008 4:31:48 PM

Maxim Yegorushkin wrote:
> On Oct 23, 1:48 pm, "Martin T." <0xCDCDC...@gmx.at> wrote:
>> Alberto Ganesh Barbati wrote:
>>> Martin T. ha scritto:
>>>> 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.
> 
> []
> 
>> ...
> 
> At this point it seems to be much simpler just to declare:
> 
>      struct city_t { string name; int pcode; };
> 
> as you mentioned in your original post and dispense with unnecessary
> macro awkwardness.
> 
> Is there a reason why you would still like to use std::pair<>?
> 

Some algorithm or container might work with std::pair so I need 
something "compatible" with it.

br,
Martin

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Martin 10/25/2008 2:33:23 PM

On 10/21/08 23:31, Martin T. 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.
>
> 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 ... ?
[snip]

Boost fusion's vector:

http://www.boost.org/doc/libs/1_36_0/libs/fusion/doc/html/fusion/container/v
ector.html

does something similar for any number of fields up to some boost
maximum (or at least it did last time I looked at the implementation
several years ago) ; however, the preprocessor generated field names
are just m0,m1,...mn.  Of course those names are even harder to read
than first and second.  However, I'm guessing that the preproccessor
magic that fusion uses to generate the vector could be adapted to
generate more readable names similar to your proposal.


HTH,

Larry



-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Larry 10/27/2008 9:19:37 AM

On Oct 27, 4:19 pm, Larry Evans <cppljev...@suddenlink.net> wrote:
> On 10/21/08 23:31, Martin T. 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.
>
> > 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 ... ?
>
> [snip]
>
> Boost fusion's vector:
>
> http://www.boost.org/doc/libs/1_36_0/libs/fusion/doc/html/fusion/cont...
> ector.html
>
> does something similar for any number of fields up to some boost
> maximum (or at least it did last time I looked at the implementation
> several years ago) ; however, the preprocessor generated field names
> are just m0,m1,...mn.  Of course those names are even harder to read
> than first and second.  However, I'm guessing that the preproccessor
> magic that fusion uses to generate the vector could be adapted to
> generate more readable names similar to your proposal.
>

Fusion provides a macro to adapt the struct of your choice (with
whatever member names you like) as a fusion sequence.

--
gpd


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply gpderetta 10/28/2008 4:23:35 PM
comp.lang.c++.moderated 10598 articles. 7 followers. Post

9 Replies
374 Views

Similar Articles

[PageSpeed] 59

  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

No std::hash for std::pair
std:pair (and tuple) provide lexicographical comparisons using the comparison operators, provided that the types held within the pair have those operators defined. operator< is a particularly useful special case because it allows pairs and tuples to be used as the key elemets in std::set and related containers. The same does not hold true for std:hash and therefore std::unordered set. Is there a rationale behind why std::pair (and tuple) don't have a hash function which, for example, hashes all the elements and xors the results? Or is the lack of such a specialisatio...

Why is std::sub_match derived from std::pair?
I wonder what where the reasons that lead to the decision, that sub_match<BiIt> is publicly derived from pair<BiIt, BiIt>, as seen in 28.9/1 of N2134? On the first sight it seems to be astonishing, that inheritance is used here, because std::pair is actually not designed for that, being actually an entity usually known as "value type". Furtheron there seem not to exist a relevant number of advantages for this: std::pair has actually no reusable member functions useful for the derived class. Even the predefined comparison operators are not reused but replaced b...

Which container
I am wriing a messaging system and I need to mantain a list of subscribers(object) to topics (string). which of the ff representations is better (and why?) typedef pair<string, list<Subscriber> > topicSubscribers ; typedef list<topicSubscribers> subscriberList ; OR typedef map<string, list<Subscriber> > topicSubscribers ; typedef list<topicSubscribers> subscriberList ; Bart Simpson <eatmyshorts@springfield.com> wrote: > which of the ff representations is better (and why?) > > typedef pair<string, list<Subscriber> > topicSub...

member function names identical to class names
When adopting the coding style of the standard C++ library, you often run into naming problems because class names are lower case, and member functions do not have get/set prefixes. For example: - The class stringstream has a member function "string stringstream::str()". It would be more logical to name it "string stringstream::string()". - The class ios_base has a member function "locale ios_base::getloc()". It would be more logical to name it "locale ios_base::locale()". Especially because the "get" prefix is never used in the standard libra...

Make a python property with the same name as the class member name
Is it possible in python to create a property with the same name as the member variable name of the class. e.g. Class X: ... self.i = 10 # marker ... property(fget = get_i, fset = set_i) Please tell me how I can do so. Because if I do so, for the statement at marker I get stack overflow for the assingm On Fri, Feb 27, 2009 at 5:59 AM, Ravi <ra.ravi.rav@gmail.com> wrote: > Is it possible in python to create a property with the same name as > the member variable name of the class. e.g. No, because accessing the property and the instance variable are *syntactically...

Constrained name value pairs or pre-filled names types?
Looking for something similar to a map type, but which allows me to define a new type (possibly via templates?) at compile time, with the expected NAMES filled in. Values will come in at runtime. so just to illustrate : supposing i have 2 valid names with expected values :- name,age so foo.name = "myname"; foo.age=99; //ok foo.address="moderated road"; // error at compile time Now, i know you might say why dont you go off and define your own class and use a map for underlying implementation? The reason i dont want to do that is that i would hav...

std::pair
std::pair is it a c++ object / c++ type or what? which header file it comes with? ====== std::pair< std::vector< int >::iterator, ====== typedef int id_type; typedef unsigned int timestamp_type; typedef std::pair<id_type, timestamp_type> entry_type; Andrew Ostry wrote: > std::pair is it a c++ object / c++ type or what? It's a template. Therefore, std::pair< int, char > is a type and std::pair< int, char > some_pair_variable; declares some_pair_variable to be a variable of that type. > which header file it comes with? #include <utility>...

class ctor argument variable name and class member variable name
I've read some code like below: class Foo { int foo; public : Foo(int foo) :foo(foo) {} }; I try it in VC2008, and it is fine. My question is :in the ctor, the name "foo" here does not cause any ambiguity, why that? Is this a standard way or just a workaround ? -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] On Nov 5, 8:06 am, zade <zhaohongc...@gmail.com> wrote: > I've read some code like below: > class Foo > { > in...

What are the naming convention for private member variable, and private and public member function?
Hi, It says in http://www.python.org/dev/peps/pep-0008/ " Method Names and Instance Variables Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability. Use one leading underscore only for non-public methods and instance variables." I am wondering what is the different between member function and member variable in term of naming convention. Regards, Peng > It says in http://www.python.org/dev/peps/pep-0008/ > > " Method Names and Instance Variables > > Use the functi...

How to implement std::tuple's sometimes std::pair constructor?
I think that std::tuple has a constructor like: template < typename ...Types > struct tuple { //... // Only valid when sizeof...(Types) == 2 template < typename T, typename U > tuple( std::pair<T, U> p ); //... }; Is there a way to implement that besides having it in a (partial) specialization when there are two parameters and omitting it for all other specializations? I'm thinking about adding constructors like these in a class template of mine, but I don't want to write a bunch of otherwise-identical special...

Academic name for associative array when used to pair column names with data
I read Chris Date's book "An Introduction to Database Systems" where he use= s the term "tuple" to describe what is commonly called a "row" in a databas= e. What would the proper term be for an associative array of the column nam= es paired with the data from a particular row (otherwise known as a hash)? For example in Perl: my @column_names =3D qw/color season sound/; my @data =3D ( [ qw/blue fall loud/ ], [ qw/red spring soft/ ], [ qw/orange winter pin_drop/ ], ); foreach my $tuple ( @data ) { my %name_needed =3D ma...

static std::vector<std::string> member and a static function
Hi, I am getting this linker error: error LNK2019: unresolved external symbol "public: static class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > & __cdecl ...... I have a static std::vector<std::string> member in the private section of my class. I am initializing/defining this static member in my cpp file like this: std::vector<std::string> M...

Defect Report: std::pair allows impl conv of pair of expl convs
20.2.2 Pairs [lib.pairs] paragraph 4 <quote> template<class T1, class T2> struct pair{/*...*/}; .... template<class U, class V> pair(const pair<U, V> &p); Effects: Initializes members from the corresponding members of the argument, performing implicit conversions as needed. </quote> (Here, for brevity, I assume: typedef std::vector<int> Vec; typedef std::vector<int>::size_type S; ) Statment 1:This allows a pair<A,B> to be *implicitly* converted to a pair<C,D>, even if the A to B and C to D conversions are only ...

Static member of class not found if class name == name of namespace it's defined in
Some time ago I started a topic on comp.lang.c++ about possible bug in g++ found by me. Although there was no general agreement as to whether it's a compiler bug or language underspecification, there was a conclusion that something was definitely wrong with my code example since g++ and Visual C++ handled it differently. I also sent a bug report to g++ bugzilla more than a month ago, but no one seemed to care as I receved no reply and bug status hasn't changed. Consider this definition: namespace Foo { int x; class Foo { public: static...

std::locale::global(std::locale("zh-CN")) Gets "Bad locale name"??
Hi everyone: I'm playing with C/C++ locale recently. I've got a program which uses Chinese character as file name or in the path of a file. When using fstream to manipulate files, I choose to use MBCS instead of Unicode, so I have to specify the locale. At first I tried setlocale(LC_CTYPE, "chinese") and it works well, however, it's a C-style locale setting, for C++, std::locale::global() is preferable. Unfortunately, I just can't set the correct locale by calling std::locale::global(). I have tried: std::locale::global(std::locale("zh-CN&quo...

Given std::map<ID,struct>, efficient way to access std::vector<struct.member>?
Hello folks, I've got an interesting little design problem and I'm looking for some advice on how best to implement an efficient solution. Here's a simplified statement of the problem that I believe outlines the relevant details: I've got a class declared as follows: --- begin example class ---- class CFilter { public: typedef struct tag_sRow { A_t A; B_t B; C_t C; ... ... ... // some number of structure members... } sRow_t; typedef std::map<key_t/*type unimportant*/, sDataRow_t> mapData_t; typedef mapDataSet_t::iterator mapiterData_t; typedef mapDataSet_t::const_iter...

member name as a class
Hi all, I don't know where to look it up in the standard, and don't know if this code is valid or not: struct movie {}; struct test { // a variable of type ::movie, named movie movie movie; }; int main() {} As a side-note, it compiles successfully with como, VC6, VC71, VC8, but it fails to compile for gcc3.3, gcc3.4.2 Best, John -- John Torjo, Contributing editor, C/C++ Users Journal -- "Win32 GUI Generics" -- generics & GUI do mix, after all -- http://www.torjo.com/win32gui/ -v1.6.3 (Resource Splitter) -- http://www.torjo.com/cb/ - Click, Build, Run! ...

name/value pair
I'm not the greatest at awk scripts yet and wondered if I could get some help. I have a file with lines like below: 2220 D list=greylist-level2 address=00.131.106.14 2221 D list=greylist-level2 address=0.222.155.234 2222 D list=greylist-level2 address=00.192.174.70 2223 D list=greylist-level2 address=0.44.238.193 2224 D list=greylist-level2 address=00.221.228.138 2225 D list=greylist-level2 address=00.135.226.234 2226 D list=greylist-level2 address=00.6.31.26 2227 D list=greylist-level2 address=00.182.115.110 2228 D list=greylist-level2 address=00.103.33.49 2229 D list=greylist-level2 ad...

union ( members with same name )
Is possible I have a union with its members having the same name as below ? union { MyType myVar; MyType myVar; MyType myVar; OtherType otherVar; } MyUnion; I am using "gcc" but it don't compile. do I need any compile option ? Thank you, Frederico Faria On 4 Jul 2003 15:38:57 -0700, fred_faria@yahoo.com.br (Frederico Faria) wrote in comp.lang.c: > Is possible I have a union with its members having the same name as below ? No. Each one must have a different name. > > union { > MyType myVar; > ...

Named a private member..
When I named a private member: class A { public: ... private: int primem; }; Should I use int primem_; or int _primem;? Which one is more like c++ style? (my english is not good.) :-( On 09/17/10 03:08 PM, Kai Wen wrote: > When I named a private member: > class A { > public: > ... > private: > int primem; > }; > > Should I use > int primem_; > or > int _primem;? > > Which one is more like c++ style? > (my english is not good.) :-( There isn't a typical C++ style for member names. Just choose one and ...

std::pair allocator?
Why doesn't std::pair have an allocator? "Mark P" <not@my.real.email> wrote in message news:NTAbe.1207$Gd7.603@newssvr21.news.prodigy.com... > Why doesn't std::pair have an allocator? A std::pair is not a container. Its purpose is not to allocate. Think of a std::pair as a record-template for inserting or extracting a record-pair to / from a given associative container. Its the associative container that handles or stores the allocation of a std::pair's contents. "Mark P" <not@my.real.email> wrote in message news:NTAbe.1207$Gd7.603@newssvr2...

Member with same name as type
I encountered this example in a C header, is the following legal? typedef long ios; struct X { ios ios; }; It complies with comeau online and Sun CC, but g++ reports /tmp/c.cc:6: error: declaration of 'ios X::ios' /tmp/c.cc:2: error: changes meaning of 'ios' from 'typedef long int ios' -- Ian Collins * Ian Collins: > > I encountered this example in a C header, is the following legal? > > typedef long ios; > > struct X > { > ios ios; > }; > > It complies with comeau online and Sun CC, but g++ reports > > /tmp/c.cc:...

Using std::pair
I've used SWIG to wrap a C++ method that returns a std::pair<x,y>. I know that Tcl is handling it correctly but I cannot figure out how to access the returned value. Consider the following sequence of Tcl commands (with output): % set valref [pValuable_fetch "BRDPA_NEW"] _004627b8_p_pValuable % set bondOptref [pValuable_castTopBondOption $valref] _004627b8_p_pBondOption % pBondOption BondOptObj -this $bondOptref % BondOptObj breakageFee MYDATE 0 _0040b2a0_p_std__pairTdouble_cDate_t % set bf [BondOptObj breakageFee MYDATE 0] _00443490_p_std__pairTdouble_cDate_t How can I...

swapping std::pairs?
Why doesn't std::pair have an overload of swap, which swaps both of it's elements? This would seem to be a natural thing to do, and allow for a more efficent implementation of swap when the elements of the pair can themselves be more efficently swapped. In a similar note, the new "tuple" class in tr1 has a similar problem. I can't see how this could lead to inefficency or a problem, but I assume it must be possible? Thank you, Chris --- [ comp.std.c++ is moderated. To submit articles, try just posting with ] [ your news-reader. If that fails, us...