When having a simple qtest which compares 2 different objects for a user-defined struct:
Test a, b = {1};
QCOMPARE(a, b);
Why is there a difference between:
(1)
static char* toString(const Test &)
{
using QTest::toString;
return toString("Test");
}
And
(2)
namespace {
char* toString(const Test &)
{
using QTest::toString;
return toString("Test");
}
} // unnamed namespace
The first one does call the function when comparing the objects, the second one does not!
As mentioned in this conclusion, there should be no difference except anonymous namespaces allow you to define translation-unit-local type. Well, here it looks like it's the opposite.
The default
QTest::toStringimplementation is a function template:Specializing this template seems to be one way to provide a custom implementation, but you are using the other one, i.e., adding a function to the
toStringoverload set. I haven't looked at the Qt sources, but it seems that the lookup for matching names to construct an overload set is performed using ADL.Now when you have this
they are in the same (global) namespace. This works, because using ADL to look for names related to
Testpulls in the global namespace, and that's where yourtoStringoverload resides. But that differs frombecause the latter is identical to
and hence when instantiating a function template for the type
Test, ADL fails to find thetoStringname asTestis not declared in the (unnamed)someRandomUniqueIdentifiernamespace. If you defineTestinside the anonymous namespace, the appropriatetoStringfunction should be invoked.The thread you linked is about
staticfunctions vs. anonymous namespaces. The issue you encounter isn't related to that, it's the lookup rules, particularly ADL.