0

I got a very annoying issue with C++ and function name resolution. consider the following code:

#include <iostream>

namespace A {
    class STA{ int i; };

    void func(STA a) {std::cout << "Namespace A\n";}
}

namespace B {
    void func(A::STA a) {std::cout << "Namespace B\n";}
}

int main(int argc, char **argv)
{
    A::STA aaa;
    func(aaa); // will compile and print out: Namespace A, I would love a compiler error
    return 0;
}

Looks like compiler check the function parameter and decide that according to those parameters it does know the function so no need to add A:: or B::

the problem here is that this code will compile. meaning to use func from namespace B I have to force B::func(aaaa). This is source of bug. I want to know if there is a way to force the compiler you refuse to compile if I am not explicit with the namespace. I was debugging a big project and I couldn't understand where was the problem. I accidentality discovered that the wrong function was call.

lilington
  • 83
  • 5
  • why should it be a compiler error? – 463035818_is_not_an_ai Apr 18 '23 at 09:36
  • This is due to argument-dependent lookup, and you can't do anything about it. – molbdnilo Apr 18 '23 at 09:37
  • 1
    this is how you can turn it into an error https://godbolt.org/z/8xEWzv11b. Though I am not actually recommending to do this – 463035818_is_not_an_ai Apr 18 '23 at 09:40
  • 1
    btw there are basically 2 questions here. 1) why ? 2) how to prevent it? The duplicate is only for 1) and i think it is appropriate because apparently you didnt know about ADL. If however you want to focus on 2) I'd be in for a reopen. In any case you should read about ADL – 463035818_is_not_an_ai Apr 18 '23 at 09:42
  • Thanks, I just follow the link to the duplicate. I understand the why but I got confused about if I should or not try to avoid it. The only issue I see is that I need to be very carefull when I use a thirdparty lib. and make sure I don't create a function with same name and same parameter that are inside that lib – lilington Apr 18 '23 at 09:56
  • 1
    There's no collision here; if `A::func` did not exist, the compiler would not look inside `B` for `func`. It would simply complain that there was no `func` that it could call. Note, too, that inside a function that's defined in `B`, an unqualified call to `func` would call `B::func`. Don't panic! – Pete Becker Apr 18 '23 at 12:03

0 Answers0