views:

174

answers:

3

Hello, 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.

+1  A: 

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();
}

}
YeenFei
+2  A: 

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.

Jan
Use the "01" button to format your code.
Johannes Schaub - litb
A: 

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;

}
Frederik Slijkerman
I'm afraid that would lead to linker errors.
UncleBens