Home > Back-end >  Forward declaration of third party library
Forward declaration of third party library

Time:10-18

I am doing a forward declaration of a struct of third party library, so that I can include third party header only in my .cpp file.

I need to forward declare them in .hpp and then in the .cpp file, I need to let third party header define them in their implementation.

// X.hpp
namespace Y {
typedef struct A A;
typedef struct B B;
void (*f1)(A*);
void (*f2)(B*);

...
...

private: 
std::unique_ptr<A, decltype(f1)> a;
std::unique_ptr<B, decltype(f2)> b;

}
// X.cpp
#include <third_party> // contains definitons and declarations of real A, B

// this is not correct, but I need to say something like this.
struct Y::A: public A {};
struct Y::B: public B {};

namespace Y {
// using A, B in the implementation
}

CodePudding user response:

The information you give is a bit limited, but assuming you have some third-party library that defines a struct A in a namespace Y, you can use it with a std::unique_ptr as follows, for the header file:

#include <memory>

namespace Y
{
  struct A; // the forward declaration
}

class MyClass
{
public:
  MyClass();
  ~MyClass();

private:
  std::unique_ptr<Y::A> a_;
};

And the .cpp file:

#include <third_party>

MyClass::MyClass() : a_{...}
{
}

MyClass::~MyClass() = default;

This ensures that the code for the destructor is compiled in a context where the full definition of Y::A is known.

CodePudding user response:

You can forward declare a struct this way:

struct A;

Reason this does not work for you is that you are using unique_ptr, which requires a definition (declaration is not enough). You can use shared_ptr instead.

Alternatively you can encapsulate the private variables into a class (defined in the cpp file, forward declared in the header file) and use pointer to that class instead of pointers to the third party structs.

  • Related