gpt4 book ai didi

c++ - 使用可变参数模板在 C++ 中定义列表类

转载 作者:太空宇宙 更新时间:2023-11-04 15:32:55 26 4
gpt4 key购买 nike

我试图在 C++11 中使用 vadiadic 模板定义一个 IntList 类,但我在语法上遇到了困难,而且我不确定如何初始化类字段。

我的最新版本如下:

template <int...>
struct IntList;

template<>
struct IntList<>{
constexpr static bool empty = true;
constexpr static int size = 0;
};

template<int Hd>
struct IntList<Hd>{
constexpr static bool empty = false;
constexpr static int size = 1;
constexpr static int head = Hd;
constexpr static IntList<> next = IntList<>();
};

template<int Hd, int... Rs>
struct IntList<Hd, Rs...>{
constexpr static bool empty = false;
constexpr static int size = sizeof ...(Rs);
constexpr static int head = Hd;
constexpr static IntList<Rs...> next = IntList<Rs...>();
};

我的列表类有 4 个字段,头字段返回列表中的第一个数字,下一个字段返回列表的“尾部”。

我有一个包含 2 个或更多数字的列表的“一般”案例和一个包含 1 个数字的列表的 2 个基本案例以及一个不包含头和下一个字段的空列表(空列表应该抛出错误当试图访问其中之一时)。

当尝试测试我的列表时,行:

IntList<1, 2, 3>::next::next;

给我以下错误:

error: 'IntList<1, 2, 3>::next' is not a class, namespace, or enumeration
IntList<1, 2, 3>::next::next;

尝试将 head 和 next 字段定义为常规(非静态)字段并在构造函数中初始化它们也会导致错误:

invalid use of non-static data member 'IntList<1, 2, 3>::head'
IntList<1, 2, 3>::head;

这让我相信我实际上应该将这两个字段都定义为“静态”。

任何关于如何定义头部和下一个字段/我做错了什么的输入,将不胜感激!

最佳答案

您可能想要声明一个类型而不是静态成员:

using next = IntList<Rs...>;

Demo

关于c++ - 使用可变参数模板在 C++ 中定义列表类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44696427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com