使用可变参数模板打印 class 对象

printing class object using variadic templates

我正在尝试了解折叠和可变参数模板。 我设计了一个非常幼稚的Tupleclass。我可以创建一个元组对象,但我想打印该对象。奇怪的是几乎所有地方都没有触及这个问题(至少到目前为止我还没有找到任何资源。 这是代码

#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...>是非法的,我使用折叠的那一行没有意义。我真的找不到一种方法来完成这项工作。有人可以帮忙吗?

只需使用递归:

// 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;

  friend std::ostream& operator<<(std::ostream& out, const Tuple& tuply) {
    out << tuply.first;
    if constexpr (sizeof...(Args) == 0) return out;
    else return out << " - " << tuply.rest;
  }

 public:
  Tuple(T&& firsty, Args&&... resty)
  : first(std::forward<T>(firsty)), rest(std::forward<Args>(resty)...) { }
};

Demo.