I have two functions that I have overloaded for my debug class:
template<class IteratorT>
inline debug&
operator()(const std::string& name,
IteratorT begin,
IteratorT end)
{
_stream << indent(internal) << "g< " << name << " : [ ";
for (auto i = begin; i != end; i++)
_stream << (*i) << " ";
_stream << "] >" << std::endl;
return *this;
}
And
inline debug&
operator()(const std::string& name,
std::vector<uint8_t>::const_iterator begin,
std::vector<uint8_t>::const_iterator end)
{
_stream << indent(internal) << "u8< " << name << " : [ " << std::hex;
std::copy(begin, end, std::ostream_iterator<uint32_t>(_stream, " "));
_stream << "] >" << std::endl;
return *this;
}
Here is a snipped of how it’s used:
int main()
{
debug log;
std::vector<uint8_t> vec;
vec.push_back(0xde);
vec.push_back(0xad);
vec.push_back(0xc0);
vec.push_back(0xde);
log("vec", vec.begin(), vec.end());
}
The output is (since it’s not being printed as hex characters I ommited the unformatted result):
g< "vec" : [ ... ] >
Instead of
u8< "vec" : [ de ad c0 de ] >
For some reason the compiler isn’t picking the correct, overloaded function.
$ g++47 --version
g++47 (GCC) 4.7.0 20120224 (experimental)
The problem in the code is that overload resolution only considers the arguments to the function and not how the result is going to be used. That means that the expression
vec.begin()(converselyvec.end()) only considers thatvecis a non-const vector, and it is thus using the non-const version.While there is an implicit conversion from
std::vector<>::iteratortostd::vector<>::const_iterator, this required conversion deems the overload as a worse candidate for resolution than the template function with the type substitution beingstd::vector<>::iterator.As of workarounds, you can overload for both
iteratorandconst_iterator(best solution, as the solution is in just the callee) or you can fix the calls by forcing the vector to be const by means of a cast:static_cast<const std::vector<uint8_T>& >(vec).begin()(which is ugly and requires the fix to be applied in all calls, which is hard to maintain)