Re: Iterators and ints get confused in template parameter
Juha Nieminen wrote:
I'm writing an STL-style data container, and this problem is puzzling
me. The following code should demonstrate the problem:
//----------------------------------------------------------
#include <iostream>
#include <list>
template<typename T>
class MyClass
{
public:
void assign(size_t amount, const T& value)
{
std::cout << amount << " " << value << std::endl;
}
template<typename InputIterator>
void assign(InputIterator first, InputIterator last)
{
while(first != last)
{
std::cout << *first << std::endl;
++first;
}
}
};
int main()
{
std::list<int> l1, l2;
l1.assign(10, 5); // ok
l2.assign(l1.begin(), l1.end()); // ok
MyClass<int> mc;
mc.assign(l1.begin(), l1.end()); // ok
mc.assign(10, 5); // error, wrong function gets called
Both '10' and '5' have the same type, 'int'. You have two functions
'assign', which are essentially overloaded. One takes two arguments,
'size_t' and 'int' (the 'T', which is 'int' for 'mc' object), the
other takes two arguments, both 'InputIterator', whichever that
might be. Which is the better match? I am guessing that you already
"know" all this since you say that you "understand *why" the problem
is happening". I spelled it out for the benefits of the others, then.
}
//----------------------------------------------------------
I'm using gcc 4.1.2.
I understand *why* the problem is happening. However, I don't
understand why it's not happening with std::list, and I have no idea
how to get around the problem (in the same way as std::list does).
I have looked at the std::list source code in the gcc C++ libraries,
and I don't see any fancy trick being used to differentiate between
the two assign() functions. Yet it just works with std::list, but it
doesn't work with my code.
Any pointers?
You could limit the range of types accepted by the 'assign' member
template by giving it a second template argument, for example, which
would become an ivalid type if the type of the argument is not
an iterator (SFINAE). It's Sunday and my brain isn't working well,
so I can't really suggest any changes to the code... Sorry.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask