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

Making a tuple-like compile-time "linked-list" with variadic templates

本文关键字:元组 linked-list 编译 变参 参数      更新时间:2023-10-16

我正在考虑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_;
};

科里鲁演示。

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