1

I got this example from cpp reference: https://en.cppreference.com/w/cpp/algorithm/find:

std::vector<int> v{1, 2, 3, 4};
auto result2 = std::find(begin(v), end(v), 2);

My first intent would have to be that both arguments begin(v) and end(v) must have the namespace specifier prefixed: std::begin(v) and std::end(v). But apparently according to the example it is also possible to leave this out. Why can I do this, in which situations can I do this and what C++ standard does this feature ship with?

glades
  • 3,778
  • 1
  • 12
  • 34
  • what is `v`? Please include a [mcve]. Depending on the type of `v` this can work or this can not work – 463035818_is_not_an_ai Jul 28 '21 at 09:51
  • This is unrelated to `std::find`. – Konrad Rudolph Jul 28 '21 at 09:54
  • @rafix07: I searched for ADL beforehand but as it seems ADL implies the namespace of the calling function from its arguments, but in this case its the other way around: the namespace of the function arguments are implied from the calling function. So its technically not "Argument" dependent lookup. – glades Jul 28 '21 at 09:55
  • @glades No. It *is* ADL, and the presence of `std::find` is irrelevant. It works the same without. – Konrad Rudolph Jul 28 '21 at 09:58
  • @KonradRudolph: how do you mean without? As I understand it, _Argument_ dependend lookup limits the set of possible namespaces for the calling function to the one of its arguments. So afaik ADL would be the other way around: find(std::begin(v), std::end(v), 2). Can you elaborate where it states that ADL would also work vice-versa? – glades Jul 28 '21 at 10:03
  • 3
    It doesn't work vice-versa. `v` is the argument, its type is in namespace `std`, so `begin(v)` resolves to `std::begin(v)`. The `std::find` is immaterial here. – StoryTeller - Unslander Monica Jul 28 '21 at 10:04
  • 1
    @StoryTeller-UnslanderMonica: Ahh of course that makes sense! Thanks! Could I then leave off the std:: from find as well? – glades Jul 28 '21 at 10:06
  • Can't say for sure. `std::vector` can use plain pointers as iterator types. If it does, ADL won't work here (`int*` has no associated namespace). It can even change between build configurations (I've seen code relying on ADL build in debug mode, only to not build in release mode). – StoryTeller - Unslander Monica Jul 28 '21 at 10:12

0 Answers0