Re: enforcing const overload of a method
Bo Persson wrote:
Rem wrote:
Please take a look at this code:
class A
{
public:
template<class XIter>
A(const XIter begin, const XIter beyond)
{}
};
#include <vector>
int main(int argc, char* argv[])
{
std::vector<int> integers;
A a1( integers.begin(), integers.end() );//No problem
std::vector<int>::const_iterator i( ++( integers.begin() ) );//
compiler doesn't like const_iterator here
A a2( i, integers.end() );//error C2660: 'A::A' : function does not
take 2 arguments
return 0;
}
What happened here is that in a2 constructor call Visual C++ 2008
was unable to choose the const version of std::vector<T>::end() -
or so I guess. The error message is very confusing.
Do you know how I can make sure that the const_iterator is picked
as a template argument instead of iterator?
Right now, you have to call end() on a const vector to get a
const_iterator. You could possibly make 'integers' const, or form a
const reference to it:
const std:vector<int>& const_integer = integer;
IMHO, it would be better to cast the result of end()
static_cast<std::vector<int>::const_iterator>(integers.end());
or even better (IMHO cleaner) to use a variable:
std::vector<int>::const_iterator e = integers.end();
Compiler will optimize it nicely.
Another approach would be:
template <typename XIter>
A make_A(const XIter & a, const XIter & b) {
return A(a, b);
}
A a = make_A<std::vector<int>::const_integer>(i, integers.end());
And finally, you don't need "++", you can use integers.begin()+1.
Anyway, the compiler will never choose the const version of end(),
because it is strictly defined by standard what happens when you call
an overloaded function on a mutable object.
The need for all these inelegant solutions turned on a yellow led
in my head. Are you sure that A shouldn't be a template? Can it
really be constructed with any pair of iterators? I'm guessing
that in your case it can, but I had to mention it and reset my led.
--
Dragan
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]