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

标签 c++ c++11 variadic-templates

我试图在 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/

相关文章:

c++ - 防止 visual studio 创建浏览信息 (.ncb) 文件

c++ - 如何将头文件放入 Bison 中的 .tab.h?

c++ - 为什么 wchar_t/unsigned short 现在是不同的,但没有类似的 char/unsigned byte 区别?

c++ - std::shared_ptr:未调用自定义删除器

c++ - 如果对象是右值,确保成员变量被移动

c++ - 从转发函数的类型推断的模板化返回类型

c++ - 如何比较两个 std::any?

c++函数返回模板类型检查

c++ - 将 std::tuple 转换为模板参数包

c++ - 可变参数模板函数,其中返回类型取决于模板参数列表