工会成员中的模板 - 声明没有声明任何内容

Template in union member - Declaration does not declare anything

本文关键字:声明 任何内 成员      更新时间:2023-10-16

我需要创建一个可以存储其内容(类型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的结合(这是任何事物的一部分(,但是在这种情况下,它应该是intnullptr_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)
    {
    }
};