简体   繁体   English

使用可变参数模板创建类似元组的编译时“链表”

[英]Making a tuple-like compile-time “linked-list” with variadic templates

I was pondering possible implementations of std::tuple (and any similar template classes with a variable number of "members" defined at compile time), and I thought perhaps one could create a "recursive type" resembling a linked list. 我正在思考std::tuple可能实现(以及在编译时定义了可变数量的“成员”的任何类似模板类),我想也许可以创建一个类似于链表的“递归类型”。 I tried compiling the following test-case: 我尝试编译以下测试用例:

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

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

The class itself compiles without error, but the instantiation throws the error wrong number of template arguments (0, should be 1 or more) . 类本身编译时没有错误,但是实例化会抛出wrong number of template arguments (0, should be 1 or more) I believe this is because TupleLite<int, double> tries to instantiate a TupleLite<double> , which tries to instantiate a TupleLite<> , for which there is no valid definition. 我相信这是因为TupleLite<int, double>试图实例化一个TupleLite<double> ,它试图实例化一个没有有效定义的TupleLite<>

Can this "recursively sized class" be salvaged? 这个“递归大小的班级”可以被抢救吗? I tried defining the "no-argument specialization" of TupleLite as follows: 我尝试将TupleLite的“无参数专业化” TupleLite如下:

template <>
class TupleLite {}

....but that doesn't seem to work, although g++ and clang++ seem to disagree on exactly why. ....但这似乎不起作用,虽然g++clang++似乎不确定为什么。

From g++ , the most relevant errors seem to be: 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++ , however, says: 然而, clang++说:

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

The primary template definition of TupleLite specifies that it requires at least one template argument, FirstType . TupleLite的主要模板定义指定它至少需要一个模板参数FirstType Since that isn't what you want to express, provide a primary template defition which ends up also handling the empty case like this: 由于这不是您想要表达的内容,因此提供主模板定义,最终也处理空案例,如下所示:

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

And one partial specializations: 还有一个部分专业:

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

Coliru Demo . Coliru演示

EDIT : Thanks to Nikos for pointing out that the empty spec was not needed in this case. 编辑:感谢Nikos指出在这种情况下不需要空的规格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM