user283145
user283145

Reputation:

Forward declare a global type inside a namespace

I want to use an 3rd party library without using its header file. My code resides in its own namespace, therefore I can't use conventional forward declaration as I don't want to pollute the global namespace. Currently I have something like that:

3rd-party-library.h----

typedef struct {...} LibData;
void lib_func (LibData *);

my-source.h-----

namespace foo {

    /*forward declaration of LibData*/

    class Abcd {
        public:
            void ghj();
        private:
            Libdata *data_;
        };
    }//namespace foo

my-source.cpp-----
#include "my-source.h"
#include <3rd-party-library.h>

namespace foo {
    typedef ::LibData LibData;
    void Abcd::ghj() {
        //do smth with data_
        }
    }//namespace foo

Is it possible to forward declare a global type in a way that it would reside in an namespace? Plain simple typedef does not work.

Upvotes: 2

Views: 3949

Answers (3)

Jan
Jan

Reputation: 1847

For a forward declaration to work, you need to forward declare an object in the proper namespace. Since the original object resides in the global namespace, you need to forward declare it in the global namespace.

If you don't like that, you can always wrap the thing in your own structure:

namespace foo {
struct libDataWrapper; }

and in your own cpp define this structure. Or you can always resort to void* and the like, if you're up to that sort of thing.

Upvotes: 7

Frederik Slijkerman
Frederik Slijkerman

Reputation: 6529

Can't you just simply wrap the include for the third-party library in its own namespace?

namespace ThirdParty {
#include "thirdparty.h"
}

namespace foo {

  ... your code

  ThirdParty::LibData *d;

}

Upvotes: 1

YeenFei
YeenFei

Reputation: 3208

since you are using pointer, i''' just forward declare a dummy object inside your own namespace, then use reinterpret_cast to bind the actual object to existing pointer.

your-source.h

namespace foo {

//forward declare
class externalObj;

class yourObj
{
public:
  yourObj();
  ~yourObj();
  void yourFunction();

private:
 externalObj* pExt;
};

}

your-implementation.cpp

#include "your-source.h"
#include "externalObj-header.h"

namespace foo {

yourObj::yourObj() :
pExt ( reinterpret_cast<externalObj*>(new ::externalObj()) )
{
}

yourObj::~yourObj()
{
}

void yourObj::yourFunction()
{
   reinterpret_cast<::externalObj*>(pExt)->externalFunction();
}

}

Upvotes: 2

Related Questions