簡體   English   中英

第三方庫的前向聲明

[英]Forward declaration of third party library

我正在對第三方庫的結構進行前向聲明,以便我只能在我的 .cpp 文件中包含第三方標頭。

我需要在 .hpp 中轉發聲明它們,然后在 .cpp 文件中,我需要讓第三方標頭在它們的實現中定義它們。

// 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
}

您提供的信息有點有限,但假設您有一些在命名空間Y中定義結構A的第三方庫,您可以將其與std::unique_ptr ,如下所示,用於頭文件:

#include <memory>

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

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

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

.cpp文件:

#include <third_party>

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

MyClass::~MyClass() = default;

這確保了析構函數的代碼在Y::A的完整定義已知的上下文中編譯。

您可以通過以下方式轉發聲明結構:

struct A;

這對您不起作用的原因是您使用的是unique_ptr ,它需要定義(聲明是不夠的)。 您可以改用shared_ptr

或者,您可以將私有變量封裝到一個類中(在 cpp 文件中定義,在頭文件中向前聲明)並使用指向該類的指針而不是指向第三方結構的指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM