Re: enforcing const overload of a method
On 4 Jul., 10:42, Rem <therealr...@gmail.com> wrote:
Please take a look at this code:
class A
{
public:
template<class XIter>
A(const XIter begin, const XIter beyond)
{}
This function signature is equivalent to
A(XIter begin, XIter beyond)
{}
for the compiler. All top-level cv-qualifiers of
parameters are ignored.
};
#include <vector>
int main(int argc, char* argv[])
{
std::vector<int> integers;
A a1( integers.begin(), integers.end() );//No problem
This is no problem, because both arguments have
the same type. The deduced type of the template
parameter for either argument of the constructor
template is exactly this type.
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.
Your guess is wrong. What happens here, is that you provide two
arguments of different type: The first of type
std::vector<int>::const_iterator
and the second of type
std::vector<int>::iterator
During type deduction of above constructor template the first result
for the template parameter XIter thus differs from the second,
and thus this function won't be selected.
Do you know how I can make sure that the const_iterator is picked as a
template argument instead of iterator?
you could use a cast for the second argument as
shown here:
A a2( i, const_cast<const std::vector<int>&>(integers).end() );
If you have a C++0x library, you can directly use the
member function cend:
A a2( i, integers.cend() );
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]