我可以在前向声明类中使用类型吗

Can I use a type in a forward declared class?

本文关键字:类型 声明 我可以      更新时间:2023-10-16

这个类有一个枚举:

class ThreadController
{
public:
  enum ThreadType { ... }
}

是否可以使用前向声明类中的ThreadType &

class ThreadController;
class ThreadWorker
{
public:
  static ThreadWorker makeThreadWorker(const ThreadController::ThreadType & type);
}

我得到以下错误:

'ThreadType' in 'class ThreadController' does not name a type

但是,既然我使用的是引用,编译器就不能对头文件中没有定义感到满意吗?

您可以使makeThreadWorker成为模板化函数。

template <typename T = ThreadController>
static ThreadWorker makeThreadWorker(const typename T::ThreadType & type)
{
}

如果T不包含ThreadType,编译器将抛出错误。(可选)添加static_assert以将T限制为仅ThreadController

static_assert(std::is_same<ThreadController, T>::value, "error");