简体   繁体   中英

C++: Instantiate object with no namespace

I'm stuck with two .hpp files that have a lot of classes / methods that share same names and so on. My problem is that A.hpp is wrapped inside a namespace so I can use whatever I want using> A::className objName(...);

But I don't know how to use anything from B.hpp , which is not wrapped inside namespace, so I can't write B::className objName(...) .

Process of demanding access to change any of .hpp files (where I would just wrap B inside namespace) would take about a day, so I'm looking for alternate and quicker solution.

Thank you.

First, and potentially safest, you can explicitly qualify look up in the global scope by prefixing a name with the unary scope operator :: :

::classFromB foo(/*...*/);
::globalFuncFromB( foo, &::globalVarFromB ); // Obviously this gets rather tedious.

Second, assuming no using directives ( using namespace A; ) or declarations ( using conflictsWithB = A::className ), or other declarations, produce a conflict, you can generally rely on unqualified look up:

classFromB foo(/*...*/);
globalFuncFromB( foo, &globalVarFromB  );

Finally, you can wrap the entire contents of an included file in a namespace:

namespace B {
#include "B.hpp"
}

This has numerous potential problems, particularly if any declarations in B.hpp are assumed to be or actually defined either in the header itself or elsewhere (implementation B.cpp?) in global scope. Not the best idea, but sometimes useful. Be very cautious if you consider this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM