Home > Net >  printing class object using variadic templates
printing class object using variadic templates

Time:12-10

I am trying to understand folding and variadic templates. I designed a very naive Tuple class. I can create a tuple object, but I would like to print the object. It seems odd that this problem hasn’t been touched almost anywhere (at least I haven’t found any resource so far. This is the code

#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)), ...);

}

probably Tuple<T, Args...> is illegal, and the line where I am using folding does not make sense. I really cannot find a way to make this work. Can someone help?

CodePudding user response:

Just use recursion:

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

  • Related