gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:59 26 4
gpt4 key购买 nike

我在考虑 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/

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