Re: Templates and const function name resolution
"Dimitar" <dimitar.gospodinov@gmail.com> skrev i meddelandet
news:1156791128.327334.276570@p79g2000cwp.googlegroups.com...
Hello,
I have the following class C and the function F:
class C
{
public:
const vector<int>& GetV() const { return m_v; }
private:
vector<int>& GetV() { return m_v; }
vector<int> m_v;
};
template<class T1, class T2>
void F(const typename vector<T1>::iterator& first,
const typename vector<T1>::iterator& last)
{
for (vector<T1>::iterator it = first; it != last; ++it)
{
const vector<T2>& v = it->GetV();
}
}
I am trying to call F as:
...
vector<C> v;
F<C, int>(v.begin(), v.end());
...
But this does not compile (with MS VC++ 7) - the compiler refuses to
find the public GetV() function, instead it finds the private one.
Yes, the compiler has to first select candidates for overload
resolution, and if one is selected, check if it is also accessible.
However, if I replace
const vector<T2>& v = it->GetV();
with
const vector<T2>& v = vector<T1>::const_iterator(it)->GetV();
the code compiles.
I am wondering why the code as presented above does not compile and
how
can I make it compile without introducing const iterator?
If you have both a const and a non-const function, the call is based
on the const-ness of the object you call it for ('*it' in this case).
You have several options, like
- make 'it' a const iterator in the for loop
- remove the private overload
- rename the const one GetConstV
Bo Persson
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]