首页 > 解决方案 > 联合成员中的模板 - 声明未声明任何内容

问题描述

我需要创建一个“节点”类,它可以存储其内容(类型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在这种情况下的联合,仅此而已。

我是否误解了模板的工作原理,还是我需要做一些不同的事情?

标签: c++templatesunions

解决方案


工会成员也需要一个名字:

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)
    {
    }
};

推荐阅读