考虑以下代码:
#include <iostream>
inline namespace N1
{
int x = 2;
}
int x = 1;
int main()
{
std::cout << N1::x;
std::cout << x;
return 0;
}
这显然给了我错误std::cout << x;
对 x 的引用不明确。
::x
也不起作用。
我明白为什么会发生这种情况,但是如何在不重命名或删除变量或命名空间的情况下解决这个问题?或者这是唯一的解决方案?
Inline namespace scoped variables have static storage duration http://en.cppreference.com/w/cpp/language/storage_duration (internal linking). So declaring
extern int x;
just before displaying x
will do it for you
Live on Coliru http://coliru.stacked-crooked.com/a/0ad316e1231bd678.
This way, the N1::x
won't be considered during name lookup, as it has static storage duration and internal linking.
目前尚不完全清楚代码为何有效,因此我提出了一个问题here https://stackoverflow.com/questions/33877510/do-inline-namespace-variables-have-static-storage-duration.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)