C++ 不允许我使用结构作为模板参数

标签 c++ templates struct

也许这是一个标题问题......但这是正在发生的事情:

编译器在行中给我一个错误:

Queue<Email> mailbox;

这是错误:

..\EmailSystem.h:25: error: ISO C++ forbids declaration of `Queue' with no type
..\EmailSystem.h:25: error: expected `;' before '<' token

队列.h:

#ifndef QUEUE_H_
#define QUEUE_H_

#include <string>
#include "EmailSystem.h"

...

template <class B>
class Queue {
 ...
};

#endif /* QUEUE_H_ */

队列.cpp:

#include "Queue.h"

...

template class Queue<Email>;

电子邮件系统.h:

#ifndef EMAILSYSTEM_H_
#define EMAILSYSTEM_H_

#include <iostream>
#include <string>
#include <vector>
#include "Queue.h"

struct Email {
    ...
};

struct User {
    std::string name;
    Queue<Email> mailbox;
};

...

#endif /* EMAILSYSTEM_H_ */

最佳答案

您有一个循环包含。 Queue.h 包括 EmailSystem.h 并且 EmailSystem.h 包括 Queue.h 所以包含守卫确保 header 在第二次被包含时无效。这意味着如果 Queue.h 是第一个被包含的,那么 Queue 将在它首次用于 EmailSystem.h 之前被声明在这一点上,它包括:

Queue<Email> mailbox;

我猜,但我发现你的模板 Queue(如果它真的是一个通用类模板)不太可能需要知道 Email 所以你应该从 Queue.h 中删除 #include "EmailSystem.h" 以解决您的问题。

关于C++ 不允许我使用结构作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7585165/

相关文章:

c++ - 在工作线程创建新 GUI 元素的地方使用 Qt

c++ - `re.sub(pattern, functor, string)` 对于 C++

templates - 如何用逗号连接领事模板的服务元数据

c++ - 结构错误表达式必须有 bool 类型

c++ - 绕行并使用 _thiscall 作为 Hook (GCC 调用约定)

c++ - 用于工作线程池和作业队列等的可移植库

c++ - 在类中重载运算符[],因此它可以从模板类中的数组返回对象

c++ - 模板的模板推导失败(中间有继承),有更好的方法吗?

有人可以解释一下为什么我们会得到以下输出吗?

json - 在golang中的json unmarshal上获取可为空的对象