Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ namespace alias and forward declaration

I am using a C++ third party library that places all of its classes in a versioned namespace, let's call it tplib_v44. They also define a generic namespace alias:

namespace tplib = tplib_v44;

If a forward-declare a member of the library in my own .h file using the generic namespace...

namespace tplib { class SomeClassInTpLib; }

... I get compiler errors on the header in the third-party library (which is being included later in my .cpp implementation file):

error C2386: 'tplib' : a symbol with this name already exists in the current scope

If I use the version-specific namespace, then everything works fine, but then ... what's the point? What's the best way to deal with this?

[EDIT] FYI for future viewers, this was the ICU library. A solution (at least in my situation) is in the comments to the accepted answer.

like image 512
Dave Mateer Avatar asked Jun 12 '10 00:06

Dave Mateer


People also ask

Can you forward declare a namespace?

There is no forward declaration of namespace.

Does C have forward declaration?

In Objective-C, classes and protocols can be forward-declared like this: @class MyClass; @protocol MyProtocol; In Objective-C, classes and protocols can be forward-declared if you only need to use them as part of an object pointer type, e.g. MyClass * or id<MyProtocol>.

What is alias in namespace?

namespace alias definition Namespace aliases allow the programmer to define an alternate name for a namespace. They are commonly used as a convenient shortcut for long or deeply-nested namespaces.

What does forward declaration do?

Forward Declaration refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program). In C++, Forward declarations are usually used for Classes.


1 Answers

It looks like there is an ugly workaround for this, but no good solution.

For ACE (with a decent explanation) and Xerces (with a snarky "this is how c++ works" comment), they define macros that you can use to do this "generically".

ACE_BEGIN_VERSIONED_NAMESPACE_DECL
class ACE_Reactor;
ACE_END_VERSIONED_NAMESPACE_DECL

XERCES_CPP_NAMESPACE_BEGIN
class DOMDocument;
class DOMElement;
XERCES_CPP_NAMESPACE_END

It looks like an unfortunate c++ artifact, try searching around in your tplib for these macros.

The standard treats namespaces and namespace aliases as different things. You're declaring tplib as a namespace, so when the compiler tries to assign an alias later, it cannot be both, so the compiler complains.

like image 60
Stephen Avatar answered Oct 18 '22 20:10

Stephen