I have encountered a situation where a call to std::sort()
works without explicitly writing the namespace. According to Using std::sort() without prefix "std" and also without "using namespace std;" compiles successfully, the compiler uses ADL and considers the namespaces of the arguments. Since vector
is in std
, it finds std::sort
.
In the following program, ADL fails for the second call to sort when using Visual Studio 2010. Since the iterators are the same, std::sort
should be findable. But the compiler says C3861 'identifier': identifier not found
. Why?
#include <algorithm>
#include <vector>
class StableSortClass
{
public:
int m_i;
};
bool lessStableSortClass(const StableSortClass & lhs, const StableSortClass & rhs) {return lhs.m_i < rhs.m_i;}
int main(int argc, char **argv)
{
std::vector<StableSortClass> vec;
// works because of ADL without std::
sort(vec.begin(), vec.end(), lessStableSortClass);
// does not compile in Visual Studio 2010
sort(vec.begin(), vec.end(), [](const StableSortClass & lhs, const StableSortClass & rhs) {return lhs.m_i < rhs.m_i;});
// compiles
std::sort(vec.begin(), vec.end(), [](const StableSortClass & lhs, const StableSortClass & rhs) {return lhs.m_i < rhs.m_i;});
return 0;
}
EDIT
To answer the comments so far:
- I don't want to rely on ADL. I found code in a header and wondered why the compiler does not complain to the missing
std::
. I then noticed that thestd::
is sometimes required and sometimes not, hence this question. C3861 'identifier': identifier not found
is the complete error message the compiler gave to me. Nothing more.- Yes, some folks do maintenance for old production systems where VS2010 is used. It could be worse ;-)