A lambda is not a function, but an object that can be called like a function. As such, it doesn't get the function-treatment and its invocation is not subject to ADL.
Does ADL work with named lambdas?
-
01-06-2022 - |
Question
Say I have a class and a named lambda in one namespace.
namespace bla {
class X { /* ... */ };
static auto lambda = []( X param ){ /* ... */ };
}
This lambda is almost equivalent to a function that has been declared inline. But can I call that lambda from another unrelated namespace without mentioning the namespace bla
using ADL (argument dependent lookup, also called Koenig lookup)?
namespace blub {
void f() {
bla::X x;
lambda( x ); // Does this compile?
}
}
Solution
OTHER TIPS
A lambda is really an object, so the question really boils down to:
Does ADL work for objects?
And the obvious answer is that it doesn't, ADL will only add functions to the set of candidates for overload resolution. Also note that if regular lookup finds anything other than a function, then ADL will not add any candidates to the overload resolution set.
namespace A {
struct S { operator int() const { return 0; } };
void f(S const &) { std::cout << "A::f\n"; }
}
auto f = [](int) { std::cout << "lambda\n"; }
namespace B {
void test() {
::A::S s;
f(s); // prints lambda
}
}
While A::f
is a better match to the call than ::f
, because ::f
is found by lookup and it is not a function, ADL won't bring any other functions into the picture.