How to resolve an ambiguous link caused by a conflicting identifier from the built-in namespace

Consider the following code:

#include <iostream> inline namespace N1 { int x = 2; } int x = 1; int main() { std::cout << N1::x; std::cout << x; return 0; } 

This obviously gives me an error on std::cout << x;

the reference to x is ambiguous.

::x also does not work.

I understand why this is happening, but how can I solve this problem without renaming or deleting variables or namespaces? Or is this the only solution?

+4
c ++
source share
1 answer

Extended variable namespace internal variables have a static storage duration (internal binding). so Announcement

 extern int x; 

before displaying x will do this for you Live on Coliru . Thus, N1::x will not be taken into account when searching for a name, since it has a static storage duration and internal binding.

It’s not entirely clear why the code works, so I track the question here .

+4
source share

All Articles