c++ - 使用可变参数模板制作类似元组的编译时 "linked-list"

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

我在考虑 std::tuple 的可能实现方式(以及任何类似的模板类,在编译时定义了可变数量的“成员”),我认为也许可以创建一个类似于链表的“递归类型”。我尝试编译以下测试用例:

template <typename FirstType, typename... OtherTypes>
class TupleLite
{
  public:
    FirstType type_;
    TupleLite<OtherTypes...> other_types_;
};

int main()
{
  TupleLite<int,double> mytuple;
}

类本身编译没有错误,但实例化抛出错误wrong number of template arguments (0, should be 1 or more) .我相信这是因为 TupleLite<int, double>尝试实例化 TupleLite<double> ,它试图实例化一个 TupleLite<> ,没有有效的定义。

能否挽救这个“递归大小的类”?我尝试定义 TupleLite 的“无参数特化”如下:

template <>
class TupleLite {}

....但这似乎行不通,虽然g++clang++似乎不同意确切的原因。

来自 g++ ,最相关的错误似乎是:

error: template specifiers not specified in declaration of ‘template<class FirstType, class ... OtherTypes> class TupleLite’
  class TupleLite
        ^
error: wrong number of template arguments (0, should be 1 or more)
 TupleLite<OtherTypes...> other_types_;
                          ^

clang++ ,然而,说:

error: extraneous 'template<>' in declaration of class 'TupleLite'
template <>
^
error: redefinition of 'TupleLite' as different kind of symbol
class TupleLite
      ^

最佳答案

TupleLite 的主要模板定义指定它至少需要一个模板参数,FirstType。由于这不是您想要表达的内容,因此提供一个主要的模板定义,它最终也像这样处理空的情况:

template <typename...>
class TupleLite{};

还有一个部分特化:

template <typename FirstType, typename... OtherTypes>
class TupleLite<FirstType, OtherTypes...>
{
  public:
    FirstType type_;
    TupleLite<OtherTypes...> other_types_;
};

Coliru Demo .

编辑:感谢 Nikos 指出在这种情况下不需要空规范。

关于c++ - 使用可变参数模板制作类似元组的编译时 "linked-list",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292435/

相关文章:

c++ - 来自通用命名空间的前向声明类(在 std::hash 中

c++ - lambda 表达式的可变参数模板

c++ - 'deep' 模板参数推导是否可行?

c++ - 我如何让这个递归规则起作用?

c++ - 以下函数的时间复杂度应该是多少?

c++ - 如何在 Qt C++ 中为数组动态分配内存?

c++ - 嵌套类的模板模板参数的可变类型模板参数和非类型模板参数如何相互约束?

c++ - 这段代码中的竞争条件是什么?

c++ - unordered_map find() 和 operator []

c++ - 代理 QtConcurrent::run 函数的可变参数模板