As a learning exercise I've been reimplementing some of the STL algorithm. Even though I've not added any using directives or using declarations for the std namespace my test code won't compile unless I explicitly prefix those functions shadowing std names.
I assume that this is due to argument dependent lookup bringing in functions from the std namespace when I pass std::vector
iterators as parameters to my functions.
A small program to illustrate my problem:
#include <vector>
#include <algorithm>
namespace danstd {
template <typename I, typename T>
I find(I b, I e, T val) {
for (; b != e; ++b) {
if (*b == val)
return b;
}
return e;
}
}
using namespace danstd;
int main() {
std::vector<int> v = {1, 2, 3};
auto i = find(begin(v), end(v), 3);
return i == end(v) ? -1 : *i;
}
When I compile, I see these error messages:
$ g++ -Wall foo.cpp
foo.cpp: In function ‘int main()’:
foo.cpp:16:37: error: call of overloaded ‘find(std::vector<int>::iterator, std::vector<int>::iterator, int)’ is ambiguous
return *find(begin(v), end(v), 3);
^
foo.cpp:5:3: note: candidate: I find(I, I, T) [with I = __gnu_cxx::__normal_iterator<int*, std::vector<int> >; T = int]
I find(I b, I e, T val) {
^~~~
In file included from /usr/include/c++/6/algorithm:62:0,
from foo.cpp:2:
/usr/include/c++/6/bits/stl_algo.h:3784:5: note: candidate: _IIter std::find(_IIter, _IIter, const _Tp&)[with _IIter = __gnu_cxx::__normal_iterator<int*, std::vector<int> >; _Tp = int]
find(_InputIterator __first, _InputIterator __last,
^~~~
In the unit test code, I've linked to above, I've wrapped my functions inside a danstd namespace and I make each call on the form danstd::function(...)
. Is there any way around having to use fully qualified names to avoid the naming conflicts with std names?