【问题标题】:printing class object using variadic templates使用可变参数模板打印类对象
【发布时间】: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&lt;T, Args...&gt; 是非法的,我使用折叠的那一行没有意义。我真的找不到方法来完成这项工作。有人可以帮忙吗?

【问题讨论】:

  • 我没有时间摆弄代码 atm,但我强烈建议您阅读 this ;) 特别是如果您刚刚开始。
  • 从描述问题开始,显示编译错误etc.
  • alagner 非常感谢我现在就阅读它

标签: c++ templates c++17 variadic-templates stdtuple


【解决方案1】:

只使用递归:

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

【讨论】:

    猜你喜欢
    • 2013-06-04
    • 2021-05-19
    • 2022-01-06
    • 2012-09-02
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多