c++ - 联合成员中的模板 - 声明未声明任何内容
问题描述
我需要创建一个“节点”类,它可以存储其内容(类型T
)或nullptr
(表示一个空节点)。
这个节点必须有元数据(比如它的年龄),当它存储一些东西和什么都不存储时。
我想出了这个(简化的)代码:
template <typename T>
struct Node
{
union T_or_null {
T;
std::nullptr_t;
};
int age;
T_or_null content;
Node(T_or_null argContent)
: age(0),
content(argContent)
{
}
};
int main()
{
Node<int> a(0);
Node<int> b(nullptr);
return 0;
}
我收到错误main.cpp:5:3: error: declaration does not declare anything [-fpermissive]
Gcc 似乎明白我正在尝试创建任何东西的联合和nullptr_t
(它是任何东西的一部分),但它应该是int
和nullptr_t
在这种情况下的联合,仅此而已。
我是否误解了模板的工作原理,还是我需要做一些不同的事情?
解决方案
工会成员也需要一个名字:
union T_or_null {
T value;
std::nullptr_t null;
};
但它们也需要手动记账才能正确处理,所以我建议你放弃联合并切换std::optional
到模型可空性:
template <typename T>
struct Node
{
int age;
std::optional<T> content;
Node(std::optional<T> argContent)
: age(0),
content(argContent)
{
}
};
推荐阅读
- django - 静态文件未使用 cookiecutter-django 保存在 S3 存储桶上
- react-native - React Native ScrollView 不滚动(我们认为问题不在于渲染,而在于渲染之上)
- c++ - 我必须使用 C++ 中的链表构建联系人列表。它目前无限循环第三次接触
- r - 如何使用包 stargazer 更改自变量的顺序
- javascript - 现在使用用户代理字符串检测 IE11 不再有问题了吗?
- c# - KeyDown 事件不会从 UWP 中的选定网格触发
- extjs - Extjs 6/7 树获得右键单击事件
- amazon-web-services - AWS CloudFormation:向其他 AWS 账户提供 CF 堆栈
- python - for 完成时打印数组内容
- c# - 是否有任何替代 MediaStreamType.photo 以获取 winforms 或 WPF 中的照片流?