c++ - std::function 中的不完整类型

标签 c++ include std-function

我有一个类似于下面的 Target 类:

class Target
{
  std::function<void(A&,B&,C&)> Function;
}

现在,这些参数类型之一(比如 A)有一个 Target 成员并尝试调用它的函数:

class A
{
  Target target;
  void Foo(B& b, C& c)
  {
    target.Function(*this,b,c);
  }
}

在某处,这两种类型出现在头文件中。鉴于循环依赖,有一个前向声明,不幸的是,一个错误:不允许指向不完整类类型的指针错误。

所以问题是 - 我该怎么办?

最佳答案

你有一个 circular dependency问题。将 target 声明为 class A 中的指针,并在构造函数中适本地分配它,并在类的析构函数中释放它:

class A
{
  A() : target(new Target) {}
  ~A() { delete target; }
  Target *target;
  void Foo(B &b, C &c)
  {
    target->Function(*this, b, c);
  }
};

如果您的编译器支持 C++11,请改用智能指针:

class A
{
  A() : target(std::unique_ptr<Target>(new Target)) {}
  std::unique_ptr<Target> target;
  void Foo(B &b, C &c)
  {
    (*target).Function(*this, b, c);
  }
};

关于c++ - std::function 中的不完整类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23035586/

相关文章:

c++ - 使用 std::function 在对象列表上调用任何对象成员函数

c++ - 将 errno.h 错误值转换为 Win32 GetLastError() 等价物

c++ - 如何在 Cython 中返回新的 C++ 对象?

c++ - 尝试以特定长度将字符串从一个复制到另一个时出现段错误?

php - 关于 PHP include 语句的问题

php - 文件包含可能存在 PHP 范围问题?

c++ - 如何在 C++ 中使用 std::function 实现策略模式

c++ - Lambda 捕获列表和复制

c++ - 检查#include 是否已经声明

c++ - 如何在 GDB 调试器命令行中调用 std::function 句柄