here is some code, that displays the oddity:
namespace ns
{
typedef int int_type;
class classus {
public:
int a = 0;
};
void print(classus c){
printf("a equals %i \n", c.a);
}
void print(int_type a){
printf("a equals %i \n", a);
}
}
int main(int argc, char* argv[])
{
ns::int_type a1 = 2;
ns::classus a2;
ns::print(a1); // this line wont work without explicit ns:: scope
print(a2); // this line works with or without explicit ns:: scope
}
This builds and runs on visual studio 2017. Intellisense is also perfectly happy with it.
It seems variables of class contained in a namespace, pollutes the entire line with that namespace scope. Is this a bug or a feature? Either way, is there some documentation about this... have not found any
The feature that is confusing you is called ADL (argument dependent lookup)
From cppreference:
Argument-dependent lookup, also known as ADL, or Koenig lookup, is the set of rules for looking up the unqualified function names in function-call expressions, including implicit function calls to overloaded operators. These function names are looked up in the namespaces of their arguments in addition to the scopes and namespaces considered by the usual unqualified name lookup.
Argument-dependent lookup makes it possible to use operators defined in a different namespace.
In your example a2
being from the namespace ns
is enough for the compiler to also consider ns
when looking for print
.
The interesting part of your example is that int_type
is also coming from ns
, though it is just a typedef and int
is not declared in ns
. Consider that a typedef does not introduce a new type (rather an alias). So a2
really is an int
.
PS: This is not specific to Visual studio. Any compiler conforming to the standard should accept the code posted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With