【发布时间】:2022-01-14 17:27:15
【问题描述】:
我正在尝试了解折叠和可变参数模板。 我设计了一个非常幼稚的 Tuple 类。我可以创建一个元组对象,但我想打印该对象。奇怪的是这个问题几乎没有在任何地方被触及(至少到目前为止我还没有找到任何资源。 这是代码
#include <iostream>
#include <string>
// this is the implementation of my own tuple using variadic templates
template <class... T>
class Tuple {};
template <class T, class... Args>
class Tuple<T, Args...> {
private:
T first;
Tuple<Args...> rest;
public:
// friends
friend std::ostream& operator<<(std::ostream& out, const Tuple<T, Args...>& tuply);
public:
Tuple(T&& firsty, Args&&... resty): first(firsty), rest(resty...){};
};
template <class T, class Args...>
std::ostream& operator<<(std::ostream& out, const Tuple<T, Args...>& tuply){
out << tuply.first;
((out << " - " << std::forward<Args>(tuply.rest)), ...);
}
可能Tuple<T, Args...> 是非法的,我使用折叠的那一行没有意义。我真的找不到方法来完成这项工作。有人可以帮忙吗?
【问题讨论】:
-
我没有时间摆弄代码 atm,但我强烈建议您阅读 this ;) 特别是如果您刚刚开始。
-
从描述问题开始,显示编译错误etc.
-
alagner 非常感谢我现在就阅读它
标签: c++ templates c++17 variadic-templates stdtuple