使用可变参数模板制作类似元组的编译时"linked-list"
Making a tuple-like compile-time "linked-list" with 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_;
};
科里鲁演示。
编辑:感谢Nikos指出在这种情况下不需要空规范。
相关文章:
- C++:TypeDef使用元组
- Pybind11:将元组列表从Python传递到C++
- 重载元组索引运算符-C++
- 在C++中,如何通过几种类型从元组中选择多个元素
- 重载Singly Linked List中的赋值运算符
- 将fold表达式与std::一起用于两个元组
- std::ranges::elements_view,用于自定义类似元组的数据
- 将元组的向量转换/构造为堆
- 专用于 std 元组的模板,而无需用户执行remove_cvref
- 将元组的向量构造成堆
- 元组由 Swig 生成的 Python 包装器返回,用于C++向量
- 将元组类型扩展为可变参数模板?
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 类内部和外部静态 constexpr 元组之间的差异
- 可变参数模板与使用元组在参数中添加不同的数据对
- 访问和打印元组中的数据,并使用 C++14 使用模板函数显示数据
- boost::包含提升单元的元组的哈希值
- 我正在寻找一种优雅的方式来从元组向量创建tuple_element向量
- 如何在可变参数模板函数中遍历可变参数元组?
- 使用可变参数模板制作类似元组的编译时"linked-list"