开发者

Why we can't include std headers within a namespace in C++

开发者 https://www.devze.com 2023-02-02 06:16 出处:网络
The following code will cause compile errors in g++4.4: // File test.cpp namespace A { #include <iostream>

The following code will cause compile errors in g++4.4:

// File test.cpp
namespace A
{
    #include <iostream>
}

int main()
{
    return 0;
}

I have this requirement because some third party library comes without namespace protected, and if I directly include these headers, my namespace is polluted.

As a result, I tried to create namespaces for thos开发者_JS百科e libraries, but if the library includes some "std headers" the above approach will fail.

Can anybody help?

Thank You!


I believe 17.4.2.1 [lib.using.headers] forbids including standard library headers in a namespace :

A translation unit shall include a header only outside of any external declaration or definition, and shall include the header lexically before the first reference to any of the entities it declares or first defines in that translation unit.

I don't think there is anything you can do besides filing a request to the library author.


This approach will most likely lead you to trouble. You could approach the problem by manually including each such standard header before entering the namespace, and the include guards would take care of not re-including the header inside the namespace.

That would take care of your current error, but it would on the other hand break too many other things --if the library is precompiled then the symbols used in your code and the symbols in the binary library would be different symbols (libname::foo() used in your code, ::foo() defined in the binary). Even if the library is header only, any fully qualified access to the library within the library itself would break (void foo() { ::bar(); } where foo and bar are inside the library).

A valid approach that you might want to try (even if cumbersome, and requiring real work) would be writting a wrapper that is within it's own namespace, and uses the library. Then include your wrapper instead of the actual library headers.

My advice, on the other hand, would be ignoring the problem altogether. Declare your own objects within your namespaces and that would take care of the possible name collisions. As long as you keep away from using namespace statements you will be fine.


Use fully qualified names when using calls to standard libraries like std::cout instead of writing using namespace std;. This way, both can coexist.

0

精彩评论

暂无评论...
验证码 换一张
取 消