Topic: template and const
Author: lars.farm@nts.mh.se (Lars Farm)
Date: 1996/03/28 Raw View
Is "pair<T1,T2>" valid as function argument where the
declaration expects "const pair<const T1,T2>&"?
This comes up in the standard library map<K,V>::insert and make_pair
template <class T1, class T2>
struct pair {
T1 first;
T2 second;
pair();
pair(const T1& x, const T2& y);
};
template <class T1, class T2>
pair<T1,T2> make_pair(const T1&, const T2&);
template <class Key, class T,
class Compare = less<Key>,
class Allocator = allocator>
class map {
...
typedef pair<const Key, T> value_type;
...
pair<iterator, bool> insert(const value_type& x);
...
};
void f( string a, string b )
{
map<string,string> m;
...
m.insert( make_pair(a,b) ); // valid c++?
make_pair yields a temporary of type pair<string,string>. temporaries are
const. insert() wants a const pair<const string,string>. So they should
both be a pair of constant strings, right? but the compilers I have access
to disagrees.
--
Lars Farm, lars.farm@nts.mh.se
---
[ comp.std.c++ is moderated. To submit articles: Try just posting with your
newsreader. If that fails, use mailto:std-c++@ncar.ucar.edu
comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
Comments? mailto:std-c++-request@ncar.ucar.edu
]
Author: "Nathan Myers, http://www.cantrip.org/" <ncm@cantrip.org>
Date: 1996/03/29 Raw View
Lars Farm <lars.farm@nts.mh.se> wrote:
>
> Is "pair<T1,T2>" valid as function argument where the
> declaration expects "const pair<const T1,T2>&"?
[It would allow: ]
> void f( string a, string b )
> {
> map<string,string> m;
> ...
> m.insert( make_pair(a,b) ); // valid c++? [yes, now.]
The definition of the template pair<> was changed at the March '96
meeting specifically to allow this.
pair<> now has a template constructor. Of course that is of little
use to you (for now) if you (like most of us) don't yet have a compiler
that supports member templates. In the meantime you might like to
write a little template function, make_map_pair<>().
If we had type deduction from constructor arguments, even make_pair<>()
would be unnecessary. Next time, next time.
Nathan Myers
ncm@cantrip.org http://www.cantrip.org/
[ comp.std.c++ is moderated. To submit articles: try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ FAQ: http://reality.sgi.com/employees/austern_mti/std-c++/faq.html ]
[ Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu ]